gpt4 book ai didi

javascript - 对于在 for..in 中检测到的属性,propertyIsEnumerable 记录 false

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

我正在努力理解 Enumerability and ownership of properties .它说:

Enumerable properties show up in for...in loops unless the property's key is a Symbol.

这是我正在玩的代码:

function Car() {
this.name = 'BMW';
}

Car.prototype.year = 1998;


var bmw = new Car();


for( var prop in bmw ) {
console.log( prop )
}

// name
// year

console.log( bmw.propertyIsEnumerable( 'name' ) ) // true
console.log( bmw.propertyIsEnumerable( 'year' ) ) // false

for..in 检测到 bmw.propertyIsEnumerable( 'year' ) 时,为什么会记录 false

最佳答案

Object.prototype.propertyIsEnumerable()

Every object has a propertyIsEnumerable method. This method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. If the object does not have the specified property, this method returns false.

var a = [];
a.propertyIsEnumerable('constructor'); // returns false

function firstConstructor() {
this.property = 'is not enumerable';
}

firstConstructor.prototype.firstMethod = function() {};

function secondConstructor() {
this.method = function method() { return 'is enumerable'; };
}

secondConstructor.prototype = new firstConstructor;
secondConstructor.prototype.constructor = secondConstructor;

var o = new secondConstructor();
o.arbitraryProperty = 'is enumerable';

console.log(o.propertyIsEnumerable('arbitraryProperty')); // returns true
console.log(o.propertyIsEnumerable('method')); // returns true
console.log(o.propertyIsEnumerable('property')); // returns false

o.property = 'is enumerable';

console.log(o.propertyIsEnumerable('property')); // returns true

// These return false as they are on the prototype which
// propertyIsEnumerable does not consider (even though the last two
// are iteratable with for-in)
console.log(o.propertyIsEnumerable('prototype')); // returns false (as of JS 1.8.1/FF3.6)
console.log(o.propertyIsEnumerable('constructor')); // returns false
console.log(o.propertyIsEnumerable('firstMethod')); // returns false

来源:Object.prototype.propertyIsEnumerable() - JavaScript | MDN

关于javascript - 对于在 for..in 中检测到的属性,propertyIsEnumerable 记录 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021159/

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