2010-07-29 86 views
2

所以我有一些JavaScript類,並且在一種方法中我使用jQuery來綁定函數來單擊事件。在這個函數中,我需要調用這個類的其他方法。在通常的js函數中,我通過"this.method_name()"來完成,但在這裏,我猜,jQuery重新定義了「this」指針。在jQuery函數中調用類方法

+1

也許會幫助,如果你粘貼一個簡短的代碼片段。 – 2010-07-29 16:49:10

回答

7

jQuery沒有重新定義this指針,但這就是JavaScript函數通常的工作原理。以不同的名稱存儲對此指針的引用,然後使用它。

var self = this; 
$("selector").click(function() { 
    self.method_name(); 
}); 

有關更多方法,請參閱this answer

+0

鏈接指向錯誤的答案。更新 – Anurag 2010-07-29 16:52:18

+0

哦哇,thx,工作。 – Tyth 2010-07-29 17:19:46

+0

@Tramp - 不客氣。但請注意,這仍然是一個拙劣的方法。而是使用'jQuery.proxy',或者甚至更好的是現在包含在標準中的'bind'方法。如果它在某些瀏覽器中不可用,則很容易定義一個 - http://stackoverflow.com/questions/3018943/javascript-object-binding-problem-inside-of-function-prototype-definitions/3019431#3019431 – Anurag 2010-07-29 17:29:59

3

有幾種不同的方法可以做到這一點。

Anurag有一個完美的例子。其他

兩種方式是jQuery的代理類(文中提到的其他答案)和「應用」功能

現在,讓我們創建一個click事件的對象:

var MyObj = function(){ 

this.property1 = "StringProp"; 

// jQuery Proxy Function 
$(".selector").click($.proxy(function(){ 

    //Will alert "StringProp" 
    alert(this.property1); 
// set the 'this' object in the function to the MyObj instance 


},this)); 


//Apply Function 
//args are optional 
this.clickFunction = function(arg1){ 
    alert(this.property1); 
}; 

$(".selector").click(this.clickFunction.apply(this,"this is optional")); 


};