有没有办法在回调中保留这个引用?

时间:2011-04-14 12:59:40

标签: javascript javascript-events callback

很难用文字解释,但这是我在代码中经常出现的内容:

var self_reference;
self_reference = this;

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

有没有办法在不需要临时变量的情况下编写它(这里是self_reference)?

3 个答案:

答案 0 :(得分:1)

不,没有。

this是上下文敏感的,this将是回调函数中的另一个对象。除非你把它复制到某个地方否则会丢失。

答案 1 :(得分:1)

您可以查看jQuery proxy函数。

e.g。

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

答案 2 :(得分: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));
相关问题