Javascript 我可以将本地变量设置为';这';在匿名回调函数中引用它?
我想在回调函数中引用'this',但不能保证'this'会引用正确的对象。创建引用“this”的局部变量并在匿名函数中使用该变量是否合适 例如:Javascript 我可以将本地变量设置为';这';在匿名回调函数中引用它?,javascript,asynchronous,this,Javascript,Asynchronous,This,我想在回调函数中引用'this',但不能保证'this'会引用正确的对象。创建引用“this”的局部变量并在匿名函数中使用该变量是否合适 例如: var MyClass = function (property) { this.property = property; someAsynchronousFunction(property, function (result) { this.otherProperty = result; // 'this' could be wron
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'
});
};
但我想看看是否还有其他策略,或者这个解决方案是否存在任何问题。是的,这很好,但不要像以前那样使用隐式全局变量,而是使用局部变量:
var myClass = this;
您所做的是确保引用正确对象的经典方法,尽管您应该在本地定义它,即: 或者,在现代浏览器中,您可以显式绑定它:
someFunc(function(result) {
this.property = whatever;
}.bind(this));
另见:
jQuery等库支持后一种功能,将其作为更多浏览器支持的代理函数,并可简化为此可重用函数:
function proxy(fn, ctx)
{
return function() {
return fn.apply(ctx, arguments);
}
}
使用它:
someFunc(proxy(function(result) {
this.property = whatever;
}, this));
我本来打算用
bind
添加另一个选项,但杰克先做了!:)
someFunc(proxy(function(result) {
this.property = whatever;
}, this));