gpt4 book ai didi

Javascript propertyIsEnumerable 返回 false 但仍然可枚举

转载 作者:行者123 更新时间:2023-11-30 12:34:20 26 4
gpt4 key购买 nike

根据 MDN :

The propertyIsEnumerable() method returns a Boolean indicating whether the specified property is enumerable

但是当我运行下面的代码时,它输出:

method info is NOT enumerable
but can be seen in for loop

var Person = function(name){
this.name = name;
};

Person.prototype.info = function(){
console.log("Name =", this.name);
};

var me = new Person('Mike');
console.log('method info is' + (me.propertyIsEnumerable('info') ? '' : ' NOT') + ' enumerable');
for(var k in me) {
if (k == 'info') {
console.error('but can be seen in for loop')
}
}

这让我很困惑。


更新

正如@RobG 所回答的,由于 propertyIsEnumerable 只检查对象本身的属性,如果我只想迭代对象的属性,我该怎么办?

最佳答案

propertyIsEnumerable只检查对象本身的属性,不考虑原型(prototype)链。所以:

me.propertyIsEnumerable('info')

返回 false 因为 me 上没有 info 属性,它在 Person.prototype 上。它出现在 for 循环中,因为它将遍历 me 的所有属性,包括从其构造函数原型(prototype)继承的属性。

由于这种行为,propertyIsEnumerable 在早期版本的 Safari 中被用作 hasOwnProperty 的替代品,其中 hasOwnProperty 要么有问题要么不存在(我不记得是哪个)。

关于Javascript propertyIsEnumerable 返回 false 但仍然可枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26580326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com