因为如果我想要参数,我需要传递一个匿名函数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()