如果我这样做:
for (var i in obj) {
if (obj.hasOwnProperty(i)) console.log("Has property: " + i);
else console.log("Doesn't have property: " + i);
}
会obj.hasOwnProperty(i)
不会回来false
?如果有,什么时候?
如果我这样做:
for (var i in obj) {
if (obj.hasOwnProperty(i)) console.log("Has property: " + i);
else console.log("Doesn't have property: " + i);
}
会obj.hasOwnProperty(i)
不会回来false
?如果有,什么时候?
在循环中使用 hasOwnProperty 的想法是在循环继承的属性时解析为 false。这避免了 Douglas Crockford 所说的“深挖”。
来自https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty的示例:
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
}
else {
alert(name); // toString or something else
}
}
来自https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty的示例- 未显示何时hasOwnProperty
可以返回 false。
这是一个测试用例,它确实表明:
// From some library or earlier in your code
Object.prototype.xxx = "xxx";
// Your object
var data = { member: "member" };
for (var key in data) {
if( data.hasOwnProperty(key) ) {
alert(key); // alert("member")
}
else {
alert(key); // alert("xxx")
}
}