JavaScript:为什么getOwnPropertyDescriptor()包含自定义的inheritance属性?
我正在学习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
是inheritance自Object.prototype
一个对象。
由于您创build了Object.prototype.x
enumerable属性,因此在迭代使用for...in
对象时for...in
您将看到该属性。
为了避免这一点,你可以
-
使
x
不可枚举:Object.defineProperty(Object.prototype, 'x', { value: 5, configurable: true, writable: true });
-
在
for...in
过滤非自己的属性在for...in
:for (var attr in areaPropDesc) if(areaPropDesc.hasOwnProperty(attr) { /* ... */ }
这是因为属性描述符本身就是一个对象,所以它可以访问Object原型上的“x”,就像环境中的所有其他对象一样。
换句话说,“x”不是来自“矩形”对象的“x”。