7

如果我这样做:

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?如果有,什么时候?

4

2 回答 2

3

在循环中使用 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
  }
}
于 2012-08-17T16:56:03.780 回答
1

来自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")
    }
}
于 2014-03-17T09:27:16.070 回答