范围当做OO javascript回调 [英] scope when doing OO javascript callbacks

查看:111
本文介绍了范围当做OO javascript回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Folks - 我想学习如何写OO Javascript,我来自as3 OO背景...
问题我有传递一个类的方法作为回调到另一个类。 。

Folks - I'm trying to learn how to write OO Javascript, I come from as3 OO background... issue I'm having is with passing a class' method as a callback to another class...

在下面的示例中,我创建一个AppController类的实例,并在其中创建一个ConnectionMonitor类的实例。我传递一个AppController的方法由ConnectionMonitor回调。回调函数工作正常,但似乎回调函数中的内容放弃了它的范围(AppController)...

in the example below, i create an instance of AppController class, and in it, i create an instance of ConnectionMonitor class. I pass one of AppController's methods to be called back by ConnectionMonitor. The calling back works fine, but seems that what's inside the callback function looses the scope of the class its in (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());
}


推荐答案

setTimeout将运行传递的函数绑定到窗口。您可以使用ES5的 绑定

setTimeout will run the passed function bound to window. You can override this with ES5's bind:

this.connection.detectInitialConnection( this.initialConnectionDetected.bind(this) );

这在旧版浏览器中无效,但提供的MDN链接有一个解决方法。

This doesn't work in older browsers, but the provided MDN link has a workaround.

这篇关于范围当做OO javascript回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆