Callback this context [duplicate]

半世苍凉 提交于 2019-12-01 12:08:04

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 );

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