首页 > 模块化代码中,callback函数如何使用全局的this变量?

模块化代码中,callback函数如何使用全局的this变量?

代码基本结构如图~
bindLeftEvent作为initLeftMenu的callback函数,但是bindLeftEvent中this已经不是整个代码块中的this,要如何使用call、apply或者其他方法使得bindLeftEvent中的this为全局的this?


有两种方法,一种是比较通用的方法,使用在外部定义个this变量,然后使用匿名函数,再使用apply就可以了,入下:

init:function(){
    var self = this;

    self.initLeftMenu(function(){
        self.bindLeftEvent.apply(self,arguments);
    })
}

第二种是es5才提供的新方法 ,使用Function.prototype.bind方法进行绑定,如下


init:function(){ var self = this; self.initLeftMenu(self.bindLeftEvent.bind(this)); }

if (!Function.prototype.bind) {
    Function.prototype.bind = function (context) {
        var oldArgs = [].slice.call(arguments).slice(1),
            fn = this;

        return function () {
            var newArgs = [].slice.call(arguments);
            fn.apply(context, oldArgs.concat(newArgs));
        };
    }
}
({
    //...
    init: function () {
        //...前面代码
        self.initLeftMenu(self.bindLeftEvent.bind(self));
    }
    //...
})

不是可以传进去么?

【热门文章】
【热门文章】