为什么for.in循环不遍历对象's原型
Why for..in loop is not traversing through an object's prototype
我阅读了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)
。如果删除了它,它也应该遍历原型。
相关文章:
- Node.js中的JavaScript原型对象效率
- 获取原型对象的名称
- 如何维护对原型对象的访问
- 文字与原型对象表示法的数据结构
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- 正在重置原型对象的构造函数属性
- 编写JS原型时,所有函数都应该使用原型对象
- 什么's是原型对象的真实名称
- Javascript - 使用数组作为函数的参数,并在创建新的原型对象时更改值
- 在原型对象 jquery 上将一个按钮与另一个按钮不同
- 原型对象
- 循环遍历数组时的原型对象
- 为什么初始化的 JavaScript 对象不包含原型对象
- JavaScript 原型对象 - 如何访问继承
- Javascript:获取此原型对象名称
- 如何在数据绑定后在 KNOCKOUT js 中使用“with”访问另一个原型对象
- 这在 JavaScript 中的原型对象中的值
- 在主干中向原型对象添加值不起作用
- 删除函数原型对象
- 为什么当我在这个JavaScript对象上使用反射时,我可以'看不到在其原型对象中定义的属性