有没有办法在回调中保持引用?

| 很难用文字解释,但这是我的代码中经常出现的内容:
var self_reference;
self_reference = this;

$(selector).bind(\'event\', function() {
  self_reference.someFunction();
});
有没有办法写一个不需要临时变量(这里为self_reference)的方法?     
已邀请:
不,没有。
this
是上下文相关的,and1ѭ将是回调函数中的另一个对象。除非您将其复制到某个地方,否则它将丢失。     
$(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));
    
您可以看一下jQuery代理功能。 例如
$.getJSON(url, $.proxy(function()
{
  // this has now got the desired context
}, this));
    

要回复问题请先登录注册