您好,我对 JavaScript 完全陌生,我正在尝试做一些事情,但是当我调用此函数时我无法理解:
this.start = function () {
this.interval = setInterval(startIncrement.call(this) , 1000);
}
startIncrement 仅执行一次。我正在尝试做 Counter 类来生成两个按钮(开始和停止)和一个文本框。所以当我这样做时:
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)
按钮的启动和停止仅具有调用 Counter 的启动和停止方法的 onclick 事件。我尝试了这个问题的所有答案setInterval only runs once on object method但它不起作用,现在我被困住了。
最佳答案
使用函数的 .call
方法会立即调用它,(第一个)参数将成为函数内容的 this
。
通过使用
setInterval(startIncrement.call(this) , 1000);
您将立即调用 startIncrement
方法,并使用它返回的任何内容作为 setInterval
的参数。除非它返回一个函数,否则这不是您想要的。
您的意思是:
setInterval(startIncrement.bind(this) , 1000);
?
.bind
将返回一个函数,当您调用它时,确保将(第一个)参数作为 this
对象。它不调用该函数。它创建一个包装原始函数的新函数,并在调用其包装的原始函数时执行少量工作来更改 this
对象。
关于javascript - 使用 .call(this) 调用 SetInterval 方法仅调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333898/