关于箭头函数里this的指向

es6箭头函数里this的指向和普通的this还是有区别的,它是创建的时候就确定的,

其实我发现箭头函数的指向就是同级下的console.log(this)里的this,这样的话就能比较简单的理解多层嵌套情况下箭头函数里this的指向问题了

var f1 = {
        f2: {
            f3: {
                f6: console.log(this),//window
                f4: () => console.log(this)
            }
        }
    };
    f1.f2.f3.f6;//window

相当于,在f4同级下放一个console.log(this)不就是箭头函数里this的指向

再加一个代码

var test = () => {
    console.log(this.a);
}
//形式上等价于
var test = function(){
    console.log(this.a);
}
//实质上等价于
function fn(){
    var that = this;
    var test = function(){
        console.log(that.a);
    }
}

这个里面test相当于箭头函数,那么它里面的this就是和它同级的this,既console.log(this)里的this了

猜你喜欢

转载自www.cnblogs.com/WildSky/p/11246693.html