Let's create a new object:
var dict = {};
Known fact is that after creating a new object, this new object inherits the Object.prototype
. So when I try to check if the prototype's properties were inherited I do "toString" in obj
for which I get true
. But when I want to put all the properties of the newly created object into an array I would see that the array is empty after finishing filling up. Have a look on the code below:
var names = [];
for (var name in dict) {
names.push(name);
};
names.length;
Fail to see why it happens.
As many said in the comments, the For-In loop enumerates only the enumerable properties in the prototype chain, and the inherited toString
property is not enumerable.
If you want to iterate through the non-enumerable properties of the object
prototype to see if "ToString" is there then you should get the object prototype and get its enumerable and non-enumerable properties using the getOwnPropertyNames
method:
var dict = {};
var objPrototype = Object.getPrototypeOf(dict);
var propertyNames = Object.getOwnPropertyNames(objPrototype);
propertyNames.length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With