打字稿中的此关键字未引用 class

This keyword in typescript doesn't refer to class

我对打字稿中的 'this' 关键字有疑问。正如您在下面看到的,我想从某些 'inside' 函数调用 method1,例如 FileReader.onloadend 方法。但是,'this' 引用 FileReader,而不是 class foo。我怎样才能更改我的代码以使其正常工作?

export class foo {

   constructor() {
       this.method2();
   }

   public method1() {
      console.log('method1 called');         // this never happens
   }

   public method2() {
      let reader: FileReader = new FileReader();

      reader.onloadend = function(e) {
          console.log(this)                  //it prints FileReader object
          this.method1();                    //I want this to be refered to class foo
      }
   }
}

使用带远箭头的新函数文字语法:

public method2() {
  let reader: FileReader = new FileReader();

  reader.onloadend = (e) => {
      console.log(this) //it no longer prints FileReader object
      this.method1();   //method1 called
  }
}

使用远箭头,this 现在总是指 class,而不是函数作用域。您可以查看 MDN 以获取有关词法 this 和短格式函数语法的更多信息。

该文档适用于 ES6,但它同样适用于 Typescript,因为它是一个严格的超集。

改变这个:

reader.onloadend = function(e) {
    console.log(this)                  //it prints FileReader object
    this.method1();                    //I want this to be refered to class foo
}

对此:

reader.onloadend = (e) => {
    console.log(this)                  //it prints FileReader object
    this.method1();                    //I want this to be refered to class foo
}

您可以阅读有关箭头函数的更多信息 here