【问题标题】:JavaScript: Why does getOwnPropertyDescriptor() include custom, inherited property?JavaScript:为什么 getOwnPropertyDescriptor() 包含自定义的继承属性?
【发布时间】:2015-01-20 16:40:46
【问题描述】:

我正在学习 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 属性的属性描述符对象中?!

【问题讨论】:

    标签: javascript node.js prototype javascript-objects


    【解决方案1】:

    问题在于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) {
          /* ... */
      }
      

    【讨论】:

    • 啊,是的。这很有道理。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-06-25
      • 2011-01-31
      • 2010-11-20
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多