ES6箭头函数的this指向

4,074 阅读1分钟

第一种解释:箭头函数中的this,指向的是函数定义位置(定义作用域)的上下文this

第二种解释:箭头函数的this是继承父执行上下文里面的this

一个简单的例子

var obj = {
    age : 20,
    say : () => {
        alert( this.age )
    }
}
obj.say();  // undefined  因为obj对象不能产生作用域,所以箭头函数相当于定义在全局作用域,this指向全局

定义对象的时候,定义对象属性,里面的this指向的一般是全局,或者这个对象所在的那个环境中的this。

复杂一层的例子

 var x = 11;
    var obj = {
      x: 22,
      methods: {
        x: 33,
        say: function () { console.log(this.x) },
        say2: () => { console.log(this.x) }
      }
    }
    obj.methods.say(); //33
    obj.methods.say2(); //11
    --------------------------------------------------
    var age = 99;
    function PersonX() {
      this.age = 0;
      setTimeout(() => {
        this.age++;
        console.log(age)
      }, 1000);
    }
    PersonX(); // 1

理解

箭头函数中,根本没有自己的this,导致内部的this就是外层代码块的this。因为它没有this,所以也就不能用作构造函数。

再来几个例子

var c=11
 function test1(){
 this.c=22;
 let d=function(){                 //普通函数的this指向window
   console.log(this.c);
 };
d();
 }
 var x=new test1();//输出11
var a=11;
 function test2(){
  this.a=22;
 let b=()=>{console.log(this.a)}
 b();
 }
 var x=new test2(); //输出22
var a = 11;
function text3 () {
    this.a = 22;
    return () => {console.log(this.a)}
}
var x = new text3()();//22