2011-04-14 78 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)); 
相关问题