2011-05-27 28 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