AbstractProduct.prototype.getFullInformation = function() { var str = ""; for (var key in this) { if(this.hasOwnProperty(key) && typeof (key) !== "function"){ console.log(typeof key); str += " " + key + ":" + this[key] + " \n"; } } return str; }; function Clothes(param) { this.ID = param.ID; this.name = param.name; this.description = param.descrip; this.price = param.price; this.images = param.images; this.reviews = param.reviews; this.bla = function() { return "tratata"; } } 

There is a method that iterates over an object and writes only its properties, without methods. But the typeof check on the function does not work, and the method is also recorded. Why? And how to fix it?

console.log (lunar.getFullInformation ());
The output should be like this, only without a method at the end, only properties.

 ID:15 name:pants description:bla bla price:201.5 images:image1,image2 material:poliester color:navy brand:puma sizes:XS,S,M,L,XL,XXL activeSize:S quantity:5 date:Sun Feb 10 2013 00:00:00 GMT+0200 (Финляндия (зима)) reviews:[object Object],[object Object],[object Object] bla:function () { console.log("Sda"); } 
  • four
    key is always a string - andreymal
  • Add an example of how you want to call this function, and what you want to get at the output - Grundy
  • @andreymal, write the answer :-) - Grundy
  • @andreymal have ideas on how to fix this? - YURII
  • 2
    @YURII, just check not the type of the key , but the type of the value for this key - Grundy

1 answer 1

As stated in the description

 for (variable in object) { ... } 

variable - different property names assigned to a variable at each iteration.

Property names are strings, so the type of the key variable in question is always "string".

Since you need to check the type of property , you first need to get it by the specified key key and only then check.

 for (var key in this) { if(this.hasOwnProperty(key) && typeof (this[key]) !== "function"){ str += " " + key + ":" + this[key] + " \n"; } } 
  • Well, with typeof enough != - Regent
  • @Regent, in this case, no difference at all :) - Grundy
  • The whole extra character to print :) - Regent