繁体   English   中英

TimeOut 中的回调 function(箭头)和 class 方法

[英]callback function (arrow) and class method in TimeOut

我想用独特的超时触发 2 个函数。
以下工作正常

    setTimeout(function() {
      function1(); // runs first
      function2(); // runs second
    }, 1000)

但就我而言,我有一个 class 方法和一个回调(箭头函数)。
它看起来像这样(最小化):

    class Timer {
      constructor(callback) {
        this.active = false;
        this.callback = callback;
      }

      cancel() {
        this.active = false;
      }

      set() {
        this.active = true;
        this.timeOut = setTimeout( function() {
          this.cancel();
          this.callback; // HERE is my problem. doesn't run, not casted as a function
        }, 1000)
      }

我收到以下错误Expected an assignment or function call and instead saw an expression 有什么技巧可以解决吗?

你不是在调用回调function,你也可以在调用前添加类型检查。

set() {
  this.active = true;
  this.timeOut = setTimeout(() => {
    this.cancel();
    typeof this.callback === 'function' && this.callback();
  }, 1000)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM