为什么for..in循环不遍历对象的原型

时间:2015-11-07 15:30:37

标签: javascript object

我正在阅读MDN' working with objects guide,并意识到我无法在实践中发表这种说法:

  

for ... in循环:此方法遍历对象及其原型链的所有可枚举属性

以下是我为测试而编写的代码:



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?!




1 个答案:

答案 0 :(得分:3)

因为您检查了obj.hasOwnProperty(i)。如果删除它,它也应该遍历原型。