我可以将本地var设置为'this'以在匿名回调函数中引用它吗?

sna*_*pop 2 javascript asynchronous this

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

例:

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

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

我建议的解决方案是:

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

但我正在寻找是否有其他策略,或者这个解决方案是否存在任何问题.

Ja͢*_*͢ck 5

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

function(property) {
    var that = this;

    someFunc(function(result) {
        that.property = whatever;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

someFunc(function(result) {
    this.property = whatever;
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

也可以看看: bind()

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

function proxy(fn, ctx)
{
    return function() {
        return fn.apply(ctx, arguments);
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

someFunc(proxy(function(result) {
    this.property = whatever;
}, this));
Run Code Online (Sandbox Code Playgroud)