使用 .call(this) 的 SetInterval 调用方法仅调用一次

SetInterval calling method using .call(this) calls it only once

你好,我是 JavaScript 的新手,我正在尝试做一些事情,但是当我调用这个函数时我无法理解:

this.start = function () {
    this.interval = setInterval(startIncrement.call(this) , 1000);
}

startIncrement 只执行一次。我正在尝试做 Counter class 生成两个按钮(开始和停止)和一个 textbox.So 当我这样做时:

var a = new Counter(); // generates object of Counter
a.init(); // generates the HTML (did that part)
a.start(); //start increasing the value of text box over period of time
a.stop(); // stops the counting (did that part)

按钮的启动和停止只是简单地调用计数器的启动和停止方法的onclick 事件。我尝试了这个问题的所有答案 setInterval only runs once on object method 但它没有用,现在我被卡住了。

使用函数的 .call 方法会立即调用它,(第一个)参数成为函数内容的 this

通过使用

setInterval(startIncrement.call(this) , 1000);

您正在立即调用 startIncrement 方法并使用它 returns 作为 setInterval 的参数。除非它 returns 是一个函数,否则这不是您想要的。

你的意思是:

setInterval(startIncrement.bind(this) , 1000);

?

.bind 将返回一个函数,当您调用它时,确保将(第一个)参数作为 this 对象.它不调用函数。它创建了一个包装原始函数的新函数,在调用它包装的原始函数时做少量工作来更改 this 对象。