我的问题可能和我没有使用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
                    }
                }
            }

最佳答案

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; }
    };
}

09-10 06:11
查看更多