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

时间:2015-10-25 19:13:03

标签: 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)

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

1 个答案:

答案 0 :(得分:3)

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

使用

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

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

你的意思是:

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

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