我正在學習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
屬性?!
啊,是的。這很有道理。 – 2014-11-22 17:01:18