for..in and hasOwnProperty

Possible Duplicate:
How do I check if an object has a specific property in JavaScript?

I found the following snippet in Twitter's JavaScript files. Why do they need to call the hasOwnProperty function to see dict has the key property? The for loop is running for each 'key' in 'dict' which means 'dict' has 'key'. Am I missing a point?

function forEach(dict, f) {
for (key in dict) {
if (dict.hasOwnProperty(key))
f(key, dict[key]);
}
}
44495 次浏览

因为如果您不这样做,它将循环遍历原型链上的每个属性,包括那些您不知道的属性(这些属性可能是由某些人破坏了本机对象原型而添加的)。

通过这种方式,可以保证只使用该对象实例本身上的键。

JavaScript 中的每个对象都是字典。这意味着“ toString”和其他所有方法都是每个 Object 的键:

var myObj = {};
console.log(myObj["toString"]);

但是这个函数是从 Object 类继承的,所以 hasOwnProperty 告诉您这个键是字典拥有的还是继承的。

"toString" in myObj; // true
myObj.hasOwnProperty("toString") // false

一个 href = “ https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global _ Objects/Object/hasOwnProperty”rel = “ nofollow norefrer”> hasOwnProperty 方法让您知道属性是直接位于对象的实例上,还是从其原型链继承的。

请考虑以下几点

function ObjWithProto() {
this.foo = 'foo_val';
}


ObjWithProto.prototype = {bar: 'bar_val'};


var dict = new ObjWithProto();
dict.foobar = 'foobar_val';

也就是说,您有一个具有属性 foofoobar反对 dict,它也从其原型链中继承了属性 bar

现在通过(修改后的)代码运行它:

function forEach(dict) {
var key;
for (key in dict) {
if (dict.hasOwnProperty(key))
console.log('has', key, dict[key]);
else
console.log('not', key, dict[key]);
}
}
forEach(dict);

你会明白的

has foo foo_val
has foobar foobar_val
not bar bar_val

这使您可以分离对象本身的属性和它继承的属性(通常是与循环无关的方法)。

此外,如果现在执行 dict.bar = 'new_bar_val';,则最后的结果将更改为 has bar new_bar_val,从而使您甚至可以区分与继承的属性同名的属性。