各位 - 我正在尝试学习如何编写 OO Javascript,我来自 as3 OO 背景... 我遇到的问题是将类的方法作为回调传递给另一个类...
在下面的示例中,我创建了 AppController 类的实例,并在其中创建了 ConnectionMonitor 类的实例。我传递了 AppController 的方法之一以供 ConnectionMonitor 回调。回调工作正常,但似乎回调函数内部的内容失去了其在(AppController)中的类的范围...
有什么想法吗?
//in the HTML
<script>
$(document).ready( function(){
new AppContoller().init();
});
</script>
//in the js file
//AppController Class
var AppContoller = function(){
this.body = $("body");
this.init = function(){
this.connection = new ConnectionMonitor();
this.connection.detectInitialConnection( this.initialConnectionDetected );
}
//callback function I pass
this.initialConnectionDetected = function(bool){
if(bool){
trace("app connected? "+bool); // logs - "app connected? true"
this.showOnlineSwf(); //thows error - "Object [object DOMWindow] has no method 'showOnline' "
}
else{
}
}
this.showOnlineSwf = function(){
trace("i'm online");
}
}
//ConnectionMonitor Class
var ConnectionMonitor = function()
{
this.detectInitialConnection = function(callbackFunction){
setTimeout(callbackFunction, 1000, [true]);
}
}
function trace(arg){
console.log(arg.toString());
}
最佳答案
修改init
以将回调绑定(bind)到原始上下文:
this.init = function() {
this.connection.detectInitialConnection(
this.initialConnectionDetected.bind(this));
}
不幸的是,bind
is not supported in all browsers ,但您可以在闭包中捕获 this
的当前值来实现类似的效果:
this.init = function() {
var that = this;
this.connection.detectInitialConnection(function(detected) {
that.initialConnectionDetected(detected);
});
}
另一种方法是使 detectInitialConnection
能够处理可选的上下文参数:
this.detectInitialConnection = function(callbackFunction, _this){
setTimeout(function() {
callbackFunction.apply(_this || this, arguments);
}, 1000, [true]);
}
然后你可以这样调用它:
this.init = function() {
this.connection.detectInitialConnection(
this.initialConnectionDetected, this);
}
每个示例的要点是从调用 detectInitialConnection
的上下文中保留对 this
值的引用。
关于javascript - 执行 OO javascript 回调时的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856967/