我正在阅读 MDN 的 working with objects guide并意识到我无法在实践中实现这一声明:
for...in loops: This method traverses all enumerable properties of an object and its prototype chain
这是我为测试这一点而编写的代码:
var obj1 = {
'one':1,
'two':2,
'three':3
}
var obj2 = Object.create(obj1);
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?!
最佳答案
因为您检查了 obj.hasOwnProperty(i)
。如果删除它,它也应该遍历原型(prototype)。
关于javascript - 为什么 for..in 循环不遍历对象的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584432/