Q4.回调函数中的this?

this指向的解释你可能知道了,但是当在某些场景下还是会误导你的,比如回调函数中的this。

不信看看下面的例子:

var a = {
    statusArr: [],
    on: function (state) {
        this.statusArr.push(state);
        return a;
    },
    fire() {
        /**
         * 是否将this存起来
         */
       
        //箭头函数
        // this.statusArr.forEach((state)=>{
        //    console.log(this);//a 对象
        //    this.actionArr[state]();
        // });

        //普通函数
        var self = this;
        this.statusArr.forEach(function (state) {
            console.log(this == global); //node环境  true
            console.log(this == window); //浏览器环境 true
            self.actionArr[state]();
        });
        //亦或是 通过bind改变回调函数中this的指向
        this.statusArr.forEach(function (state) {
            console.log(this);
            this.actionArr[state]();
        }.bind(this));
    },
    actionArr: {
        jump: function () { },
        run() { console.log('run !!!') },
        actionArr: {
            jump: function () { },
            run: function () { },
            fire: function () { }
        }
    }
}
a.on('run').fire();

解决问题的办法:回调函数作为参数传过去的。就是普通函数。

误解:认为箭头函数中的this是this.statusArr

 //箭头函数
        // this.statusArr.forEach((state)=>{
        //    console.log(this);//错误猜测:this为this.statusArr
        //    this.actionArr[state]();
        // });

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值