TypeScript:this指向问题、箭头函数

案例

定义 Student 类,有 age 属性,有 grow() 长大方法,调用 grow() 方法时,让 age 属性加1

定义类

class Student{
  age:number = 20

  grow():void {
    console.log("grow() 中的this:",this)
    console.log("长大一岁")
    this.age ++
    console.log("今年:",this.age)
  }
}

创建对象并调用方法

let lilei:Student = new Student()

lilei.grow()

执行结果正常:

长大一岁
今年: 21

this指向问题

在 setTimeout() 中调用 grow() 方法

setTimeout(lilei.grow,1000)

执行结果错误:

长大一岁
今年: NaN

分析问题

因为 grow() 方法被传入到 setTimeout() 中,当 1 秒后 setTimeout() 内部调用这个函数时,它是以直接调用 grow() 的方式执行的,调用时 this 指向 全局 或 undefined,

所以 this.age ++ 就变成了:

  • undefined.age ++
  • 全局.age ++

this 在传递过程中 丢失 了,因为它不再是以 lilei.grow() 的方式被调用。

解决

使用箭头函数

箭头函数的 this 不是由调用方式决定的,而是由 它在代码中所处的位置(外层作用域) 决定的。它 “记住” 了定义时所在环境的 this

代码:

setTimeout(()=>lilei.grow(),1000)

原文出处:/show_1GW21oW1ndyK.html