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?!
这正是人们进入货物提示时的问题if(obj.hasOwnProperty(i)) – Bergi
@Bergi谢谢您的宝贵意见 – Nojan