我的问题可能是相同的,并且具有与此here相同的动机,我没有使用jQuery。我想要一个javascript解决方案。
我的对象如下所示:
function Person(name, age, weight) {
this._name = name;
this._weight = weight;
this._age = age;
this.Anatomy = {
Weight: this._weight,
Height: function () {
//calculate height from age and weight
return this._age * this._weight;
//yeah this is stupid calculation but just a demonstration
//not to be intended and here this return the Anatomy object
//but i was expecting Person Object. Could someone correct the
//code. btw i don't like creating instance and referencing it
//globally like in the linked post
}
}
}
答案 0 :(得分:3)
this.Anatomy = {
//'this' here will point to Person
this.f = function() {
// 'this' here will point to Anatomy.
}
}
内部函数this
通常指向一个级别的下一个事物。解决这个问题最一致的方法是
this.Anatomy = {
_person: this,
Weight: this._weight,
Height: function () {
//calculate height from age and weight
return _person._age * _person._weight;
}
}
或者你也可以这样做
function Person(name, age, weight) {
this.Anatomy = {
weight: weight,
height: function() { return age*weight; }
};
}