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

发布于 2022-09-01 12:52:23 字数 257 浏览 7 评论 0

图片描述

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

断肠人 2022-09-08 12:52:23

有两种方法,一种是比较通用的方法,使用在外部定义个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)); }
留蓝 2022-09-08 12:52:23
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));
    }
    //...
})
瀞厅☆埖开 2022-09-08 12:52:23

不是可以传进去么?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文