javascript - 执行 OO javascript 回调时的范围

标签 javascript jquery oop callback

各位 - 我正在尝试学习如何编写 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/

相关文章:

javascript - 如何在 Chrome 扩展中获取远程 javascript 文件

javascript - 以 Angular 将文本转换为html格式

javascript - 正则表达式小组赛

model-view-controller - 四种设计模式如何融入 MVC 范式?

javascript - Node.js 中的面向对象设计

javascript - 如何防止用户为每种情况选择单选按钮?

javascript - 将对象传递给函数时检索索引

javascript - Angular拖放——如何给onStart回调函数传递参数

javascript - 实时访问 html 输入并在 html-element 中显示

javascript - 原型(prototype)与类