回调此上下文

use*_*338 1 javascript callback this

在App中:

var bootstrap = new Bootstrap();
bootstrap.init( this, this.onBootstrapComplete );
Run Code Online (Sandbox Code Playgroud)

在Bootstrap中:

this.init = function( app, completeHandler ){
    _app = app;
    _completeHandler = completeHandler;
        ...
}

...

var _allReady = function(){
        _completeHandler( _app );
}
Run Code Online (Sandbox Code Playgroud)

回到应用程序:

this.onBootstrapComplete = function( app )
{
        app.something();
        app.someValue = ...
}
Run Code Online (Sandbox Code Playgroud)

我想在onBootstrapComplete中获取上下文.它工作但看起来不正确:)

如果让我们说,我想直接从应用程序调用onBootstrapComplete,我会打电话给它这个 .onBootstrapComplete().

我怎么能这样做,所以我的onBootstrapComplete看起来像这样:

this.onBootstrapComplete = function()
{
        this.something();
        this.someValue = ...
}
Run Code Online (Sandbox Code Playgroud)

tmu*_*sch 5

我建议使用underscore.js.有关详细信息,请参见http://underscorejs.org/#bind.

this.onBootstrapComplete = _.bind( function() {
   ...
   this.someFunction(); // this context is available now
   ... 
}, this );
Run Code Online (Sandbox Code Playgroud)