回拨此背景下[复制](Callback this context [duplicate])

2019-07-18 19:32发布

这个问题已经在这里有一个答案:

  • 如何访问正确的`this`回调里面? 10个回答

在应用程序:

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

在引导:

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

...

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

早在应用程序:

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

我想进去onBootstrapComplete 背景下。 它的工作原理,但它看起来不正确的:)

如果让我们说,我想直接从应用程序调用onBootstrapComplete,我将不得不调用它.onBootstrapComplete( )。

我如何能做到这一点,所以我的onBootstrapComplete看起来是这样的:

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

Answer 1:

我会建议使用underscore.js。 见http://underscorejs.org/#bind了解更多信息。

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


Answer 2:

this当函数被调用时评估。 假设你使用this函数内部f

基本上有两种方式来调用f

(expr).f()如果f被称为某个对象的属性, this将评估该对象expr
f()在这种情况下, this将计算为window

既然你传递的功能bootstrap ,它只能调用函数为f()

你可以使用一个封闭:

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

或者,你可以用一个函数来f.apply()适当的功能:

function bind(context, f){
    return function() {
        return f.apply(context, arguments);
    }
}

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

或与ECMAScript的5, 已经是一个bind函数 [MDN] :

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


文章来源: Callback this context [duplicate]