[英]JS. properties in prototype weird behaviour
我試圖了解如何在Node.js支持的網絡游戲中使屬性與原型一起使用。
推理:而不是執行以下操作: Player.attributes.pow.value
當它Player.pow
時,它將更容易閱讀: Player.pow
注意:我不想使用函數,因為Player.pow()
使您感覺像是不僅僅是返回值。
因此,為了測試它的工作方式,我做了一個快速的模型並注意到了一個奇怪的行為,盡管它不能確定我是否應該這樣做:
function Player() {
this.attributes = {
pow: {
base: 3,
value: 3,
attChanges: [],
multiplier: 0,
calculateValue: function() {
var multiplier = this.multiplier;
var value = 0;
this.attChanges.forEach( function(att) {
value += att.value; // For some reason this.value returns NaN in the forEach, this is a way around that...
multiplier += att.multiplier;
});
this.value = this.base + value;
this.value *= (1 + multiplier / 100);
}
}
}
//Change a attribute and calculate it's value
this.attributes.pow.attChanges.push({value: 3, multiplier: 0});
this.attributes.pow.calculateValue();
}
Player.prototype.sayHello = function() {
console.log("hello");
}
Player.prototype = {
get pow() {
return this.attributes.pow.value;
}
}
var p = new Player();
p.sayHello(); // Error
console.log(p.pow);
console.log(p.pow);
p.sayHello();
它說TypeError: p.sayHello is not a function
但是,如果我將其放在定義屬性的下面,它就可以工作
Player.prototype = {
get pow() {
return this.attributes.pow.value;
}
}
Player.prototype.sayHello = function() {
console.log("hello");
}
var p = new Player();
p.sayHello(); // hello
console.log(p.pow); // 6
console.log(p.pow); // 6
p.sayHello(); // hello
這里發生了什么? 這是一個壞方法嗎? 我在這里看到了一個示例: JS defineProperty和prototype這是當前的第二個答案。
當為pow
實例變量分配prototype
,您將擦除為附加了sayHello
方法的原型的先前定義,因此,在切換聲明時,首先進行分配,然后將實例方法添加到新原型中所以一切都按預期進行。
如果要使用get
方法定義屬性而不重新定義整個原型對象,請嘗試如下操作:
Object.defineProperty(Player.prototype, "pow", {
get: function() {
return this.attributes.pow.value;
}
});
然后,您可以相對於sayHello
聲明以任何順序放置該聲明,而不必擔心意外的副作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.