2015-11-07 45 views
0

我是通过MDN的working with objects guide阅读穿越,并意识到,我不能在实践中,这种说法出现:为什么for..in循环不通过对象的原型

的for ... in循环:这方法遍历对象的所有枚举的属性和它的原型链

下面是我为这个测试编写的代码:

var obj1 = { 
 
\t 'one':1, 
 
\t 'two':2, 
 
\t 'three':3 
 
} 
 

 
var obj2 = Object.create(obj1); 
 
\t obj2.test = 'test'; 
 
// Let's see what's inside obj2 now 
 
console.info(obj2); 
 
// Yep! the __proto__ is set to obj1 
 

 
// This lists the object properties and 
 
// returns them as a string, nothing special! 
 
function showProps(obj, objName) { 
 
    var result = ""; 
 
    for (var i in obj) { 
 
    if (obj.hasOwnProperty(i)) { 
 
     result += objName + "." + i + " = " + obj[i] + "\n"; 
 
    } 
 
    } 
 
    return result; 
 
} 
 

 
// According to MDN the for..in loop traverses all 
 
// enumerable properties of an object and its prototype chain 
 
// https://goo.gl/QZyDas 
 
console.info(showProps(obj2, 'obj2')); 
 

 
// But in the console you can see that showProps returns 
 
// only the obj2.test property for obj2, meaning that it 
 
// hasn't traveresed through it's prototype chain, do you know why?!

+0

这正是人们进入货物提示时的问题if(obj.hasOwnProperty(i)) – Bergi

+0

@Bergi谢谢您的宝贵意见 – Nojan

回答

3

因为你有一个支票obj.hasOwnProperty(i)。如果你删除它,它也应该遍历原型。

+0

哦!那是我的一个愚蠢的错误。谢谢! – Nojan