2014-11-22 93 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」。