[英]Can I set a local var to 'this' to reference it inside an anonymous callback function?
我想在回调函数中引用'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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.