我正在学习 JavaScript 和 Node.js,我对 Object.getOwnPropertyDescriptor()
函数有疑问。考虑以下顶级代码:
var rectangle = {
width: 10,
height: 5,
get area() {
return this.width * this.height;
}
};
Object.prototype.x = 5;
var areaPropDesc = Object.getOwnPropertyDescriptor(rectangle, "area");
for (var attr in areaPropDesc) {
console.log("areaPropDesc["+attr+"] is: "+areaPropDesc[attr]);
}
当我执行上面的代码时,这是输出:
areaPropDesc[get] is: function area() {
return this.width * this.height;
}
areaPropDesc[set] is: undefined
areaPropDesc[enumerable] is: true
areaPropDesc[configurable] is: true
areaPropDesc[x] is: 5
为什么 x
属性包含在 area
属性的属性描述符对象中?!
最佳答案
问题是 areaPropDesc
是一个继承自 Object.prototype
的对象。
由于您创建了 Object.prototype.x
可枚举属性,当您使用 for...in
迭代对象时,您将看到该属性。
为了避免这种情况,您可以
使
x
不可枚举:Object.defineProperty(Object.prototype, 'x', { value: 5, configurable: true, writable: true });
过滤
for...in
中的非自有属性:for (var attr in areaPropDesc) if(areaPropDesc.hasOwnProperty(attr) { /* ... */ }
关于JavaScript:为什么 getOwnPropertyDescriptor() 包含自定义的继承属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27079929/