Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
typescript中的这个关键字不';I don’我指的是课堂_Typescript_Typescript1.8 - Fatal编程技术网

typescript中的这个关键字不';I don’我指的是课堂

typescript中的这个关键字不';I don’我指的是课堂,typescript,typescript1.8,Typescript,Typescript1.8,我对typescript中的“this”关键字有问题。正如您在下面看到的,我想从一些“内部”函数调用method1,例如FileReader.onloadend方法。Hovewer,“this”引用文件阅读器,而不是类foo。如何更改代码以使其正常工作 export class foo { constructor() { this.method2(); } public method1() { console.log('method1 called

我对typescript中的“this”关键字有问题。正如您在下面看到的,我想从一些“内部”函数调用method1,例如FileReader.onloadend方法。Hovewer,“this”引用文件阅读器,而不是类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
和缩写函数语法的更多信息,请查看

本文档适用于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
}
您可以阅读有关箭头函数的更多信息