Iterating over properties requires this additional hasOwnProperty
check:
(遍历属性需要此附加的hasOwnProperty
检查:)
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// do stuff
}
}
It's necessary because an object's prototype contains additional properties for the object which are technically part of the object.
(这是必需的,因为对象的原型包含该对象的其他属性,这些属性在技术上是对象的一部分。)
These additional properties are inherited from the base object class, but are still properties of obj
. (这些附加属性是从基础对象类继承的,但仍然是obj
属性。)
hasOwnProperty
simply checks to see if this is a property specific to this class, and not one inherited from the base class.
(hasOwnProperty
仅检查该属性是否是该类的特定属性,而不是从基类继承的属性。)
It's also possible to call hasOwnProperty
through the object itself:
(也可以通过对象本身调用hasOwnProperty
:)
if (obj.hasOwnProperty(prop)) {
// do stuff
}
But this will fail if the object has an unrelated field with the same name:
(但这将失败,如果对象具有一个不相关的同名字段:)
var obj = { foo: 42, hasOwnProperty: 'lol' };
obj.hasOwnProperty('foo'); // TypeError: hasOwnProperty is not a function
That's why it's safer to call it through Object.prototype
instead:
(这就是为什么通过Object.prototype
调用它更安全的原因:)
var obj = { foo: 42, hasOwnProperty: 'lol' };
Object.prototype.hasOwnProperty.call(obj, 'foo'); // true
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…