Reputation: 10390
MDN states:
Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated.
So I tried this:
var x = {a: "I am a"};
var z = Object.create(x);
for( i in z )
{
console.dir( i );
if( i == "hasOwnProperty" ) {
console.log( 'found hasOwnProperty' );
}
}
Outputs only a
but not hasOwnProperty
. Why?
Upvotes: 2
Views: 259
Reputation: 1
As answered above, each property of an object has an 'enumerable' flag. When the flag set to false the property will not be enumerated when iterating over object properties.
Object.prototype.hasOwnProperty is non-enumerable which mean is 'enumerable' flag set to false.
You can read an article I wrote on the topic here to deepen your knowledge.
Upvotes: 0
Reputation: 3892
Because hasOwnProperty is not enumerable , you can test it using
console.log(Object.getOwnPropertyDescriptor(Object.prototype, "hasOwnProperty").enumerable)
Upvotes: 1
Reputation: 288100
Because Object.prototype.hasOwnProperty
is non-enumerable:
Object.getOwnPropertyDescriptor(Object.prototype, 'hasOwnProperty')
.enumerable // false
Therefore, it's not iterated by the for...in
loop.
Upvotes: 8