我可以设置一个局部变量为'this'在匿名回调函数中引用它
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;
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定