2009-06-26 42 views
24
var UI$Contract$ddlForm_change = function() { 

    //'this' is currently the drop down that fires the event 
    // My question is can I change the context so "this" represents another object? 
    this = SomeObject; 

    // then call methods on the new "this" 
    this.someMethod(someParam); 
}; 

這是可能的嗎? 謝謝, 〜ck在聖地亞哥我可以更改javascript「this」的上下文嗎?

+0

請參閱此問題的答案:http://stackoverflow.com/questions/456967/javascript-how-to-set-this-variable-easily – molf 2009-06-26 20:54:04

+2

yepp,或多或少是http:// stackoverflow的副本。 com/questions/456967/javascript-how-to-set-this-variable-easily 接受的答案是使用call()/ apply(),請參閱https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply – VolkerK 2009-06-26 20:56:05

回答

39

不,這是不可能的。

可以調用與指定的值的方法爲(使用method.apply()/method.call()),但你不能重新分配關鍵字,this

7

J-P是正確的。這不可能。請參閱JavaScript語言規範文檔ECMA-262。你可以從這裏下載標準:

http://www.ecma-international.org/publications/standards/Ecma-262.htm

該文件是ECMA-262.pdf和39頁上,部分10.1.7。

10.1.7這

沒有與 每一個活躍的執行上下文相關聯的此值。 該值取決於調用者和 正在執行的代碼的類型,並且當控制進入 執行上下文時確定爲 。與執行上下文 關聯的此值 是不可變的。

注意「是不可變的」。即不能改變。

9

你不能改變this所指的裏面的的功能。

但是,您可以通話在特定語境的功能 - 讓this是指一個特定的對象 - 通過使用callapply

相關問題