arm*_*ive 1 javascript timer object anonymous-function setinterval
由于我需要将匿名函数传递给setInterval我是否需要参数,因此我尝试使用以下代码。最初我让它调用this.countUp,但是当它返回时,NaN我做了一些阅读并.call(this)在 SO 上找到了解决方案。然而,当我将它与匿名函数(我承认我有点迷茫)结合起来时,我现在得到了TypeError: this.countUp is undefined了 Firebug。
我想我不需要使count可访问性,也不需要playBeep方法,但让我们假装我想要这样我就可以理解我在这段代码中做错了什么。
function workout() {
var beep = new Audio("beep1.wav");
this.timerWorkout; //three timers in object scope so I can clear later from a different method
this.timerCounter;
this.timerCoolDown;
this.count = 0;
this.startWorkout = function() {
alert(this.count);
this.timerWorkout = setTimeout(this.playBeep, 30 * 1000); //workout beep - 30 seconds
this.timerCounter = setInterval(function() {this.countUp.call(this)}, 1000); //on screen timer - every second
}
this.startCoolDown = function() {
this.timerCoolDown = setTimeout(this.playBeep, 10 * 1000); //cooldown beep - 10 seconds
}
this.playBeep = function() {
beep.play(); //plays beep WAV
}
this.countUp = function() {
this.count++;
document.getElementById("counter").innerHTML = this.count;
}
}
var workout1 = new workout()
Run Code Online (Sandbox Code Playgroud)
内部startWorkout使用bind(this):
this.timerCounter = setInterval(function() {this.countUp()}.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)