2011-05-27 37 views
1

我的问题可能是相同的,并具有相同的动机,因为这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 
        } 
       } 
      } 

回答

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

感谢,但创建引用Person对象私有变量这是我唯一的出路?我不能做任何事情来解决问题 – Deeptechtons 2011-05-27 08:08:05

+0

@Deeptechtons你也可以直接使用范围内的参数。 – Raynos 2011-05-27 08:38:08

+0

这很容易感谢;] – Deeptechtons 2011-05-27 08:45:16

相关问题