ES6语法---箭头函数/关于this指向

this指向问题:

ES5:
    var obj = {
        x:1,
        func:function(){
            console.log(this.x);
        },
        test:function(){
            //定时器为异步
            setTimeout(function(){
                alert(this);
                this.func();
            },10)
        }
    }
    obj.test();//定时器里的this永远指向于window
    //以前解决是使用var _this = this;

es6:
    箭头函数的this始终指向我们定义时的this
    var obj = {
        x:1,
        func:function(){
            console.log(this.x);
        },
        test:function(){
            setTimeout(()=>{
                alert(this);//obj
                this.func();
            },10);
        }
    }
    obj.test();

猜你喜欢

转载自blog.csdn.net/mytljp/article/details/79200198