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

Why for..in loop is not traversing through an object's prototype

本文关键字:原型 对象 遍历 for in 循环 为什么      更新时间:2023-09-26

我阅读了MDN的《使用对象指南》,意识到我无法在实践中实现这一声明:

对于。。。循环中:此方法遍历对象及其原型链的所有可枚举属性

这是我为测试这个而写的代码:

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)。如果删除了它,它也应该遍历原型。