JavaScript:利用setInterval()调用类方法[duplicate]

问题描述 投票:0回答:1

我正在使用类方法制作一个简单的时钟。这是代码:

class clock{
  constructor(date){
    this.hour = date.getHours();
    this.minute = date.getMinutes();
    this.second = date.getSeconds();
  }

    updateHours(){
      if (this.hour==24){
        this.hour= 0;
      } else this.hour++;
    }
    updateMinutes(){
      if (this.minute==60){
        this.minute= 0;
        this.updateHours();
      }
      else this.minute++;
    }

    updateSeconds(){
      if (this.second ==60){
        this.second = 0;
        this.updateMinutes();
    } else{this.second++;}
      return (console.log(`${this.hour}:${this.minute}:${this.second}`)); 
}
}

let date = new Date();
let myClock = new clock(date);

setInterval(myClock.updateSeconds(), 1000);


案例1:

以上输出一行,并且从不重复。在调试器中,该程序似乎只停留在setInterval()行,而从未返回所提供的函数。为什么会这样?

======

案例#2:

  • setInterval(myClock.updateSeconds,1000)

当我不包含函数的括号时,我应该得到函数的描述,对吗?为什么此输出undefined:undefined:NaN

======

案例3:

  • setInterval(“ myClock.updateSeconds()”,1000)

当我在函数周围加上引号时,一切都开始正常运行

======

请详细说明setInterval()的功能以及这些情况之间的关系。我虽然有一个正确的想法(从某种意义上说,仅对函数进行评估并接受返回值,如案例1所示)。有什么帮助!谢谢!

javascript setinterval class-method
1个回答
1
投票

您没有正确使用setInterval。您需要传递将在以后执行的函数或类方法。当前,您正在自己执行该方法,并将该方法的返回值传递给setInterval

您还需要将bind方法传递给类的实例,因为当您将方法传递给setInterval时,它会丢失this引用。 this将指向window对象,而不是您的类的实例。

这样做吧:

setInterval(myClock.updateSeconds.bind(myClock), 1000);

codesandbox example

Mdn Function.bind()

© www.soinside.com 2019 - 2024. All rights reserved.