因爲我需要傳遞一個匿名函數到setInterval
如果我想要參數,我嘗試使用下面的代碼。本來我打電話給this.countUp
,但由於返回NaN
我做了一些閱讀,發現SO上的.call(this)
解決方案。但是,當我將它與匿名函數(我承認自己有點霧)相結合時,我現在在Firebug中獲得了TypeError: this.countUp is undefined
。JavaScript中的類變量和setInterval
我想我不需要使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()
完美的作品。謝謝你的時間。 – armadadrive
:)閱讀'bind()',你會使用它很多。 – vivek