我试图了解在遍历对象键时使用hasOwnProperty()
检查的目标。据我所知,在两种情况下都将对每个对象属性(不多,不少)执行迭代:带hasOwnProperty()
或不带hasOwnProperty()
。例如,在下面的代码中,带有hasOwnProperty()
检查的结果和不带有hasOwnProperty()
的结果相同:
const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}
const resultWithHasOwnProperty = [];
const resultWithoutHasOwnProperty = [];
for(key in obj) {
if(obj.hasOwnProperty(key)) {
resultWithHasOwnProperty.push(obj[key])
}
}
for(key in obj) {
resultWithoutHasOwnProperty.push(obj[key])
}
console.log("Result WITH hasOwnProperty check: ", resultWithHasOwnProperty);
console.log("Result WITHOUT hasOwnProperty check: ", resultWithoutHasOwnProperty);
所以我的问题是:为什么以及何时应该使用ojit_code检查?
我再改一下我的问题:如果不进行ojit_code检查,我们总会遍历所有现有属性吗?
注意,这个问题并不是真正的重复。
最佳答案
该文档表明:
hasOwnProperty
方法确保您正在检查的属性直接在对象的实例上,而不是从其原型(prototype)链继承。如果不检查,它将遍历原型(prototype)链上的每个属性。
const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}
obj.prototype = {foo: 'bar'};
P / s:注意表示:
JavaScript不保护属性名称
hasOwnProperty
;因此,如果存在对象可能具有该名称的属性的可能性,则必须使用外部hasOwnProperty
以获得正确的结果:var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
因此,您需要使用:
Object.prototype.hasOwnProperty.call(foo, 'bar');