Javascript - 范围在回调中丢失

Xou*_*boy 3 javascript

我有以下代码:

var myPage = {};
myPage.component = function(callback){

    var somethingHappened = true;

    if (somethingHappened){
        callback();
    }
};

myPage.main = function(){

    // Initialise.
    this.init = function(){

        // make an instance of my component
        this.component = new myPage.component( this.callback );

        // need my utility function here
        this.doSomethingUseful();
    };

    // Callback to be executed when something happs in the component.
    this.callback = function(){
        this.doSomethingUseful(); // doesn't work
    };

    // A useful utility that needs to be accessible from both the 
    // init() and callback() functions
    this.doSomethingUseful = function(){
        // some utility stuff
    };
};
new myPage.main().init();
Run Code Online (Sandbox Code Playgroud)

在从组件执行回调函数时,确保myPage.main范围可用的最佳方法是什么?

Mat*_*ple 6

使用绑定:

this.callback = function(){
    this.doSomethingUseful(); // doesn't work
}.bind(this);
Run Code Online (Sandbox Code Playgroud)