【问题标题】:Angular 2 "this" unable to access global variable in nested functionAngular 2“this”无法访问嵌套函数中的全局变量
【发布时间】:2016-12-10 06:15:36
【问题描述】:

我对 Angular 2 很陌生。想问一下如何在 startTimer() 中访问“task_title”。 我从 console.log() 得到的一切都是未定义的。我相信“this”指向函数本身,所以我无法获得“task_title”的值。

无论如何我可以在嵌套函数中访问 Typescript 中的全局变量吗?

export class DashboardComponent {

    task_title: string;

    myTimer = setTimeout(this.startTimer, 2000);

    updateTask(event: any){
        clearTimeout(this.myTimer);
        this.task_title = event.target.value;
        this.myTimer = setTimeout(this.startTimer, 2000);
    }

    startTimer() {
        console.log(this.task_title);
        this.myTimer = setTimeout(this.startTimer, 2000);
    };
}

结果:未定义。

【问题讨论】:

    标签: javascript angularjs function typescript angular


    【解决方案1】:

    使用调用或应用

    myTimer = setTimeout(this.startTimer.call(this), 2000);
    
    myTimer = setTimeout(this.startTimer.apply(this), 2000);
    

    【讨论】:

      【解决方案2】:

      为此使用参考,例如 var self=this

      export class DashboardComponent {
      
      var self=this;
      
      
      task_title: string;
      
      myTimer = setTimeout(self.startTimer, 2000);
      
      updateTask(event: any){
          clearTimeout(self.myTimer);
          self.task_title = event.target.value;
          self.myTimer = setTimeout(self.startTimer, 2000);
      }
      
      startTimer() {
          console.log(self.task_title);
          self.myTimer = setTimeout(self.startTimer, 2000);
      };
      }
      

      【讨论】:

      • 我喜欢这个答案。当我把它放到我的代码中时,我使用了一个变量名,比如 classScope 或 outerScope 而不是 self。
      【解决方案3】:

      使用箭头函数或.bind(this)保留this的范围

      myTimer = setTimeout(this.startTimer.bind(this), 2000);
      myTimer = setTimeout(() => this.startTimer(), 2000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-05
        • 1970-01-01
        • 2011-07-23
        • 1970-01-01
        • 2019-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多