This question already has answers here:
How to access the correct `this` inside a callback?
                                
                                    (10个回答)
                                
                        
                                3年前关闭。
            
                    
在应用中:

var bootstrap = new Bootstrap();
bootstrap.init( this, this.onBootstrapComplete );


在Bootstrap中:

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

...

var _allReady = function(){
        _completeHandler( _app );
}


回到应用程式:

this.onBootstrapComplete = function( app )
{
        app.something();
        app.someValue = ...
}


我想在onBootstrapComplete中获得此上下文。
它有效,但看起来不正确:)

如果说我想直接从App调用onBootstrapComplete,则必须将其命名为this.onBootstrapComplete(this)。

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

this.onBootstrapComplete = function()
{
        this.something();
        this.someValue = ...
}

最佳答案

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

this.onBootstrapComplete = _.bind( function() {
   ...
   this.someFunction(); // this context is available now
   ...
}, this );

09-25 16:49