【问题标题】:Confuse with TS and Angular using setTimeoutFunction使用 setTimeoutFunction 与 TS 和 Angular 混淆
【发布时间】:2020-02-25 23:28:32
【问题描述】:

我正在尝试使用 Angular 和 TS 进行一些非常简单的 Ionic 练习。我有一个简单的按钮,单击它会更改文本,然后几秒钟后我希望再次更改该文本。

我很困惑为什么“this.text”不能工作,具体取决于超时功能的使用方式。

这不起作用。 (this.text 未定义)

export class HomePage {
  constructor() { }

  text = "Default";

  onChangeText() {
    this.text = "Changed!";
    setTimeout(
      this.onBackToDefault
      , 2000);
  }

  onBackToDefault() {
    this.text = "Default";
  }
}

虽然这有效

export class HomePage {
  constructor() { }

  text = "Default";

  onChangeText() {
    this.text = "Changed!";
    setTimeout(() => {
      this.onBackToDefault();
    }
      , 2000);
  }

  onBackToDefault() {
    this.text = "Default";
  }
}

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    这是因为this 在函数内部使用时指的是函数本身。在箭头函数中使用时,它指的是外部作用域。

    在第一个示例中,您传递的是整个函数,而在第二个示例中您使用的是箭头函数。

    第一个例子也可以这样写:

    onChangeText() {
      this.text = "Changed!";
      setTimeout(function () {
        this.onBackToDefault();
    //       <------ 'this' is scoped to the anonymous function
      }, 2000);
    }
    

    【讨论】:

      【解决方案2】:
      setTimeout(
        this.onBackToDefault
      , 2000);
      

      在这个例子中,setTimeout 方法只知道其中声明的元素。因此,所有使用 this. 的元素都将是未定义的。

      您需要通过 pharanteses 使用 setTimeout 才能使用外部参数:

      setTimeout(() => {    
      // do stuff    
      }, 2000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        相关资源
        最近更新 更多