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

标签 javascript setinterval function-calls

您好,我对 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/

相关文章:

c - 如何在函数中调用文件指针

c++ - 汇编函数调用是否导致所有寄存器被压入堆栈?

javascript - 如何使用 fromTemplateUrl 的新变体将参数传递给 Ionic 模式?

javascript - 在一个 div 中居中多个 div

javascript - 如何使用 VANILLA JS 将类添加到嵌套的 Dom 元素

javascript - jQuery 中的对象原型(prototype)函数中断

javascript - 没有箭头功能的setInterval函数

jquery - setInterval 只运行一次?

javascript - 为什么只打印第二个函数调用的返回值?

javascript - 为什么 Angular 服务中的 setInterval 只触发一次?