简体   繁体   English

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

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

I would like to reference 'this' in a callback function, but there is no guarantee that 'this' will refer to the correct object. 我想在回调函数中引用'this',但不能保证'this'将引用正确的对象。 Is it appropriate to create a local variable referencing 'this' and use that variable inside the anonymous function? 创建引用“ this”的局部变量并在匿名函数中使用该变量是否合适?

Example: 例:

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

The problem is, the asynchronous function may call the provided callback from an arbitrary context (which is often outside of my control, eg when using libraries). 问题是,异步函数可以从任意上下文调用提供的回调(这通常在我的控制范围之外,例如在使用库时)。

My proposed solution is: 我建议的解决方案是:

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

But I was looking to see if there are other strategies, or if this solution is problematic in any way. 但是我一直在寻找是否还有其他策略,或者该解决方案是否有问题。

What you've done is the classical way of making sure you refer to the correct object, though you should define it locally , ie: 您所做的是确保引用正确对象的经典方法, 尽管您应该在本地定义它 ,即:

function(property) {
    var that = this;

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

Alternatively, in modern browsers you can bind it explicitly: 或者,在现代浏览器中,您可以显式绑定它:

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

See also: bind() 另请参见: bind()

Libraries such as jQuery support the latter functionality as a proxy function that more browsers support and can be simplified into this reusable function: 像jQuery这样的库支持后一种功能作为更多浏览器支持的代理功能,并且可以简化为这种可重用的功能:

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

And to use it: 并使用它:

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

是的,那很好,但是不要像您一样使用隐式全局变量,而要使用局部变量:

var myClass = this;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM