2014-11-22 95 views
1

我正在学习JavaScript和Node.js,并且我有一个关于Object.getOwnPropertyDescriptor()函数的问题。请看下面的顶级代码:JavaScript:为什么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属性?!

回答

1

问题是areaPropDesc是继承自Object.prototype的对象。

由于您创建了Object.prototype.x enumerable属性,因此当您使用for...in迭代对象时,您将看到该属性。在for...in

Object.defineProperty(Object.prototype, 'x', { 
    value: 5, 
    configurable: true, 
    writable: true 
}); 
  • 过滤器不自己的属性:

    为了避免这种情况,你可以

    • x不可枚举

      for (var attr in areaPropDesc) if(areaPropDesc.hasOwnProperty(attr) { 
          /* ... */ 
      } 
      
  • +0

    啊,是的。这很有道理。 – 2014-11-22 17:01:18

    2

    这是因为属性描述符本身就是一个对象,所以它可以访问对象原型上的“x”,就像您环境中的所有其他对象一样。

    换句话说,“x”不是来自“矩形”对象的“x”。