2015-11-07 44 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