【问题标题】:This keyword in typescript doesn't refer to class打字稿中的这个关键字不引用类
【发布时间】:2016-08-18 14:23:26
【问题描述】:

我对打字稿中的“this”关键字有疑问。正如您在下面看到的,我想从一些“内部”函数调用 method1,例如 FileReader.onloadend 方法。然而,'this' 引用 FileReader,而不是类 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
      }
   }
}

【问题讨论】:

    标签: typescript typescript1.8


    【解决方案1】:

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

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

    使用远箭头,this 现在总是引用类,而不是函数范围。您可以查看MDN,了解更多关于词法this 和简写函数语法的信息。

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

    【讨论】:

      【解决方案2】:

      改变这个:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-03
        • 1970-01-01
        • 1970-01-01
        • 2017-02-26
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        • 2013-03-17
        相关资源
        最近更新 更多