迭代对象属性和原型链的JavaScript

迭代对象属性和原型链的JavaScript,javascript,inheritance,prototype,prototypal-inheritance,prototype-chain,Javascript,Inheritance,Prototype,Prototypal Inheritance,Prototype Chain,国家: 此外,当迭代对象的属性时,原型链上的每个可枚举属性都将被枚举 所以我试了一下: 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' ); } } 仅输出a,但不输出hasOwnProperty。为什么

国家:

此外,当迭代对象的属性时,原型链上的每个可枚举属性都将被枚举

所以我试了一下:

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' );
    }
}

仅输出
a
,但不输出
hasOwnProperty
。为什么?

因为
Object.prototype.hasOwnProperty
不可枚举:

Object.getOwnPropertyDescriptor(Object.prototype,'hasOwnProperty')
.enumerable//false

因此,它不会被
for…in
循环迭代。

因为hasOwnProperty不可枚举,所以可以使用

console.log(Object.getOwnPropertyDescriptor(Object.prototype, "hasOwnProperty").enumerable)

如上所述,对象的每个属性都有一个“可枚举”标志。当标志设置为false时,在对象属性上进行迭代时不会枚举属性

Object.prototype.hasOwnProperty不可枚举,这意味着“可枚举”标志设置为false


你可以读一篇我写的关于这个话题的文章来加深你的知识。

谢谢。“可枚举”是什么意思?这可能是我的误解。@RobertRocha属性有一些内部标志:[[Writable]]、[[Enumerable]]和[[Configurable]]。如果属性的[[Enumerable]]标志设置为
true
,则它将由for in枚举枚举。看见