2011-04-14 26 views
0

很難用語言來解釋,但這裏是我經常在我的代碼:有沒有辦法在回調中保持引用?

var self_reference; 
self_reference = this; 

$(selector).bind('event', function() { 
    self_reference.someFunction(); 
}); 

有沒有寫,而不需要一個臨時變量(這裏self_reference)的方法嗎?

回答

1

不,沒有。

this是上下文敏感的,而this將是回調函數中的一個不同的對象。除非你將它複製到某個地方,否則它會丟失。

1

你可以看看jQuery proxy函數。

例如

$.getJSON(url, $.proxy(function() 
{ 
    // this has now got the desired context 
}, this)); 
+0

'call'不好 - 你必須在調用的時候傳遞值,如果你不把它拷貝到一個臨時變量,它會丟失。我會假設jQuery的代理只是一個包裝,有效地使一個臨時變量。 – Quentin 2011-04-14 13:05:43

+0

好點 - 我會編輯 – 2011-04-14 13:10:27

1
$(selector).bind('event', (function() { 
    this.someFunction(); 
}).bind(this)); 

Function.prototype.bind是ES5擴展的功能。

您可以使用_.bind作爲跨瀏覽器替代或使用$.proxy

$(selector).bind('event', (_.bind(function() { 
    this.someFunction(); 
}, this)); 

$(selector).bind('event', ($.proxy(function() { 
    this.someFunction(); 
}, this)); 
相關問題