我正在尝试使用Person.energy属性创建一个Person类,该属性包含Person.energy.value数字和一个恢复Person.energy.value的Person.energy.rest函数。
当我定义Person.energy时,我可以根据this.ability属性设置属性。但是当我尝试更新方法中的属性时,我失去了授予访问权限的范围。我已经设计了一个例子来解释我的意思......
在下面的Person.energy定义中,访问this.ability变量以设置Person.energy.initial和.value变量。这似乎工作正常,因为我可以在创建对象后控制变量.log。但是,当我尝试访问相同的this.ability变量作为Person.energy.rest函数的一部分时,它是未定义的。这似乎是一个范围问题。
我知道我没有很好地组织我的班级方法和属性,但我不知道正确的方法是什么。 什么是一个好的javascript类模式来定义仍然可以访问父级的兄弟属性的属性方法?
==代码==
function Person() {
this.init = function() {
//later: more complex var assignment
var talent = 0.5;
var skill = 0.5;
return [talent, skill];
};
[this.talent, this.skill] = this.init();
this.calculate();
return this;
}
Person.prototype.calculate = function() {
this.ability = this.talent * this.skill;
this.energy = {
initial: this.ability * 100,
value: this.ability * 100
};
this.energy.rest = function() {
console.log(this.ability, " <--- this.ability out of scope");
var amount = this.ability * Math.random();
this.value = this.value + amount;
};
};
p = new Person();
console.log(p.energy.value, " <-- calculated using this.ability");
p.energy.rest();
== Console.log ==
25 <-- calculated using this.ability
undefined <--- this.ability out of scope
答案 0 :(得分:3)
Person.prototype.calculate = function() {
var oPerson = this;//will be referring to person object which will have scope across this function.
this.ability = this.talent * this.skill;
this.energy = {
initial: this.ability * 100,
value: this.ability * 100
};
this.energy.rest = function() {
console.log(oPerson.ability, " <--- this.ability out of scope");
var amount = oPerson.ability * Math.random();
this.value = this.value + amount;
};
};