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

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

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

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

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

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

   我们可以看以下的等价写法:

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

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

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

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

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

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

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

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

如上代码,我们如果直接用实例来调用,则没什么差异。

但是,当我们先赋值给变量,由于fun2是绑定调用者的,所以这里为全局变量。

扫描二维码关注公众号,回复: 4877331 查看本文章

所以直接定义箭头函数属性的效果在于它直接绑定了实例,可以直接使用,这个对应react的jsx中使用是比较方便的,不然使用fun2模式,就需要手动绑定this再使用。

   

猜你喜欢

转载自www.cnblogs.com/chianquan/p/10257723.html