我可以设置一个局部变量为'this'在匿名回调函数中引用它

Can I set a local var to 'this' to reference it inside an anonymous callback function?

本文关键字:回调 函数 引用 this 设置 一个 局部变量 我可以      更新时间:2023-09-26

我想在回调函数中引用'this',但不能保证'this'将引用正确的对象。创建一个引用"this"的局部变量并在匿名函数中使用该变量是否合适?

的例子:

var MyClass = function (property) {
  this.property = property;
  someAsynchronousFunction(property, function (result) {
    this.otherProperty = result; // 'this' could be wrong
  });
};

问题是,异步函数可以从任意上下文中调用提供的回调(这通常不在我的控制范围内,例如在使用库时)。

我提出的解决方案是:

var MyClass = function (property) {
  this.property = property;
  var myClass = this;
  someAsynchronousFunction(property, function (result) {
    myClass.otherProperty = result; // references the right 'this'
  });
};

但是我想看看是否有其他的策略,或者这个解决方案是否有任何问题。

你所做的是确保你引用了正确的对象的经典方法,尽管你应该在本地定义,即:

function(property) {
    var that = this;
    someFunc(function(result) {
        that.property = whatever;
    }
}

或者,在现代浏览器中,你可以显式地绑定它:

someFunc(function(result) {
    this.property = whatever;
}.bind(this));

参见:bind()

像jQuery这样的库支持后一种功能,作为代理函数,更多的浏览器支持,可以简化为这个可重用的函数:

function proxy(fn, ctx)
{
    return function() {
        return fn.apply(ctx, arguments);
    }
}

使用它:

someFunc(proxy(function(result) {
    this.property = whatever;
}, this));

可以,但不要像以前那样使用隐式全局变量,而是使用局部变量:

var myClass = this;