2011-05-27 29 views
0

這裏是爲什麼「這」始終是在原型窗口的JavaScript類

function Person(name, age, weight) { 
    this._name = name; 
    this._weight = weight; 
    this._age = age; 
} 

Person.prototype = { 
    Anatomy: { 
     Weight: this._weight, 
     Height: (function() { 
      //calculate height from age and weight 
     }) 
    } 
} 

我預計Anatomy.weight爲60,當我跑這個代碼代碼:

​​

令我驚訝它是未定義的。在檢查時,似乎this指的是全局對象窗口。現在什麼這裏發生了:( 我預計this._weight指人從粗略計算物品重量,否則,這應該有被稱爲解剖最少,因爲它是一個對象。可能有人澄清疑問

回答

4

你不能。到this僅在可用功能如果你使用它,它指的是全局對象的一種可能的解決辦法是這樣的:

function Anatomy(weight) { 
    this.Weight = weight; 
    this.Height = [...]; 
} 

function Person(name, age, weight) { 
    this._name = name; 
    this._weight = weight; 
    this._age = age; 
    this.Anatomy = new Anatomy(this._weight); 
} 

我不知道這是不是最好的解決辦法,但它的我現在能想到的最好的。

+0

顯然明白,不能從我上面所解釋的完成。那麼應該怎麼做?這不是最好的回答被投票 – Deeptechtons 2011-05-27 06:23:24

+0

@deeptechtons,我編輯答案提供一個替代。看到這裏還有一個工作jsfiddle:http://jsfiddle.net/C3puH/ – 2011-05-27 06:29:21

+0

你贏得了比賽,感謝那整潔的代碼 – Deeptechtons 2011-05-27 06:44:11

0

這沒有什麼與原型做。

當您在瀏覽器中工作時,您的上下文(this)被設置爲window對象。這使您可以撥打setTimeoutalert等。就好像它們是全球功能一樣。即任何你的腳本都是全局的window對象的一種方法。

這在其他Javascript主機中並不是這樣,例如,在node.js中

+0

爲什麼是這樣的,都有相同的答案!所以我應該怎麼做的東西工作,因爲我期望包裝內關閉 – Deeptechtons 2011-05-27 06:25:51

1

this根據範圍進行更改,範圍僅受功能影響。因此,由於Person.prototype只是一個不在函數中的對象,因此this引用全局對象,它在瀏覽器中往往是window

編輯:例如修復

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

所以你建議與人類做什麼來獲得我想要的結果 – Deeptechtons 2011-05-27 06:25:02

+0

@deeptechtons我不知道爲什麼你要添加功能的原型,因爲你將用新的方式創建對象。將上面的例子添加。 – 2011-05-27 06:27:11

+0

我不明白,原型是專爲此目的而設計的?我錯過了什麼 – Deeptechtons 2011-05-27 06:31:31

相關問題