关于箭头函数的关键字this的指向问题

272 阅读3分钟

默认指向在定义它时,它所处的对象,而不是执行时的对象,定义它的时候,可能环境是window(即继承父级的this)

箭头函数 看起来是匿名函数的简写。但是还是有不一样的地方。 箭头函数中的this是词法作用域, 由上写文确定

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};

箭头函数修复了this的指向, this 总是指向词法作用域, 也就是外层调用者obj:

var obj = {
    birth: 1990,

    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25

如果使用箭头函数,以前的那种hack写法 就不需要了:

var that = this;

由于this 在箭头函数中已经按照词法作用域绑定了, 所以施一公call 或者apply() 调用函数的时候, 无法对this 进行绑定, 即 传入的第一个参数被忽略:

var obj={
    birth:2018,
    getAge:function(year){
     var b =this.birth;//2018
     var fn = (y)=>y-this.birth //this.birth 仍然是2018
     return fn.call({birth:200},year)
  }
}
obj.getAge(2020)

For example:

//es5
var fn = function(a, b){return a+b}

//es6   直接被return时候可以省略函数体的括号 
const fn=(a,b) => a+b;

//es5
var foo = function(){
    var a=20;
    var b= 30;
    return a+b;
}

//es6
const foo=()=>{
    const a= 20;
    const b=30;
    return a+b  
}

// 注意这里   箭头函数可以替代函数表达式但是不能替代函数声明

再回到this 上面来,箭头函数样意义上面来说没有this. 如果使用了this 那么就一定是外层this .不会自动指向window对象。所以也就不能使用call/apply/bind来改变this指向

var person = {
    name: 'tom',
    getName: function() {
        return this.name;
    }
}

//使用es6 来重构上面的对象
const person = {
    name:'tom',
    getName:()=>this.name
}

//这样编译的结果就是
var person ={
    name:'tom',
    getName:function getName(){return undefined.name}
}

在ES6中,会默认采用严格模式,因此this也不会自动指向window对象了,而箭头函数本身并没有this,因此this就只能是undefined,这一点,在使用的时候,一定要慎重慎重再慎重,不然踩了坑你都不知道自己错在哪!这种情况,如果你还想用this,就不要用使用箭头函数的写法。

// 可以稍做改动
const person = {
    name: 'tom',
    getName: function() {
        return setTimeout(() => this.name, 1000);
    }
}

// 编译之后变成
var person = {
    name: 'tom',
    getName: function getName() {
        var _this = this;  // 使用了我们在es5时常用的方式保存this引用
        return setTimeout(function () {
            return _this.name;
        }, 1000);
    }
};

this 的指向可以按照以下顺序判断:

  • 全局环境中的 this

    * 浏览器环境:无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this 都指向全局对象 window;

    * node 环境:无论是否在严格模式下,在全局执行环境中(在任何函数体外部),this 都是空对象 {};

  • 是否是 new 绑定:如果是 new 绑定,并且构造函数中没有返回 function 或者是 object,那么 this 指向这个新对象