typescript 属性默认值使用箭头函数 this指向问题

今天注意到前端小伙伴用react 定义component class的方法的时候是经过箭头函数的方式,表示好奇。javascript

class Test extends React.Component {
  public fun1 = () => {
    console.log(this);
  };

  fun2() {
    console.log(this);
  }
}

 如上代码中fun1的定义方式。因而感到好奇,fun1中的this是什么。前端

   若是咱们套用箭头函数的概念,咱们可能认为,这中间的this是否会指向环境变量global或window。然而却不是这样的,而是指向new Test()实例。java

   咱们能够看如下的等价写法:react

class Test extends React.Component {
  constructor() {
    super();
    this.fun1 = () => {
      console.log(this);
    };
  }

  fun2() {
    console.log(this);
  }
}

也就是在属性默认值中定义的箭头函数,等价于构造函数中的定义,全部this指向的是实例。函数

 

那么为什么要用定义箭头函数属性的方式来定义方法呢?this

它和fun2的方式的this指向的不是都是实例吗?spa

const obj = new Test();
obj.fun1();// 指向obj
obj.fun2();// 指向obj

//差别
const fun1=obj.fun1;
const fun2=obj.fun2;

fun1();// 指向obj
fun2();// global

如上代码,咱们若是直接用实例来调用,则没什么差别。code

可是,当咱们先赋值给变量,因为fun2是绑定调用者的,因此这里为全局变量。component

 

因此直接定义箭头函数属性的效果在于它直接绑定了实例,能够直接使用,这个对应react的jsx中使用是比较方便的,否则使用fun2模式,就须要手动绑定this再使用。blog

相关文章
相关标签/搜索