javascript - 为什么 for..in 循环不遍历对象的原型(prototype)

标签 javascript object

我正在阅读 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/

相关文章:

javascript - 如何在 Javascript 中使用循环显示对象的特定部分

python - 在 python 中使用 heapq 获取优先级列表时出现问题

Javascript getElementById <图像>

javascript - "You should not use <Switch> outside a <Router>"尽管可用 BrowserRouter

javascript - 如何在 Angular 8 中正确使用 setValue

Javascript:是否可以有一个在创建对象/字符串时自动触发的函数?

java - 使用不同类型的循环获得相同的结果

javascript - Gatsby 设置背景图像 CSS-In-JS(情感)

javascript - 当焦点在文本框上时显示弹出框,模糊时隐藏它,但如果单击弹出框则不显示

HTML 'td' 宽度和高度