Callback this context [duplicate]

泄露秘密 提交于 2020-01-30 02:47:20

问题


in App:

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

in Bootstrap:

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

...

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

back in App:

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

I wanted to get this context inside onBootstrapComplete. It works but it doesn't look right :)

If let's say I wanted to call onBootstrapComplete directly from App, I would have to call it this.onBootstrapComplete( this ).

How can I do it so my onBootstrapComplete looks like this:

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

回答1:


I would recommend using underscore.js. See http://underscorejs.org/#bind for further information.

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



回答2:


this is evaluated when the function is called. Say you use this inside a function f.

There are basically two ways to call f:

(expr).f() if f is called as a property on some object, this will evaluate to that object expr.
f() In this case, this will evaluate to window.

Since you pass the function to bootstrap, it can only call the function as f().

You could use a closure:

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

Alternatively, you can use a function to f.apply() the function appropriately:

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

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

Or with ECMAScript 5, there is already a bind function[MDN]:

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


来源:https://stackoverflow.com/questions/14546821/callback-this-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!