我正在制作一个有两个阶段的计时器,我忘了在我给定时器对象的函数中初始化一些变量。然而它似乎没有任何问题。
例如,使用timerObj.startTime,我知道我将它添加到对象并在那里定义然后在timerObj.start()中。然而,没有在全局或在区间函数内定义的currentTime,minutesLeft和secondLeft(我没有使用timerObj作为前缀)仍然完全正常工作。这些是否与timerObj.startTime?
相同var timerObj = {workDuration : 60000, breakDuration : 60000, currentPhase : "work"};
document.addEventListener("DOMContentLoaded", function(){
document.getElementsByTagName("button")[4].addEventListener("click", timerObj.start);
document.getElementsByTagName("button")[5].addEventListener("click", timerObj.stop);
document.getElementsByTagName("button")[6].addEventListener("click", timerObj.pause);
});
timerObj.changeTime = function(durationType, durationChange) {
return timerObj[durationType] = timerObj[durationType] + durationChange;
};
timerObj.start = function() {
timerObj.startTime = new Date().getTime();
if (timerObj.timeLeftOnPause === undefined){
timerObj.timeLeftOnPause = timerObj[timerObj.currentPhase + "Duration"];
}
timerInterval = setInterval(timerObj.interval, 100);
};
timerObj.interval = function() {
currentTime = new Date().getTime() - timerObj.startTime;
timerObj.timeLeft = timerObj.timeLeftOnPause - currentTime;
minutesLeft = numberDecorator(Math.floor(Math.ceil(timerObj.timeLeft / 100) / 600));
secondsLeft = numberDecorator(Math.floor((Math.ceil(timerObj.timeLeft / 100) / 10) % 60));
displayTime = minutesLeft + " : " + secondsLeft;
document.getElementsByClassName(timerObj.currentPhase + "-timer-display")[0].innerHTML = displayTime;
if (currentTime >= timerObj.timeLeftOnPause) {
timerObj.stop();
timerObj.currentPhase === "work" ? timerObj.currentPhase = "break" : timerObj.currentPhase = "work";
if (timerObj.currentPhase === "break"){
timerObj.start();
}
}
return timerObj.timeLeft;
};
timerObj.pause = function(){
timerObj.timeLeftOnPause = timerObj.timeLeft;
clearInterval(timerInterval);
}
timerObj.stop = function() {
clearInterval(timerInterval);
timerObj.timeLeftOnPause = timerObj.workDuration;
document.getElementsByClassName(timerObj.currentPhase + "-timer-display")[0].innerHTML =
numberDecorator(timerObj[timerObj.currentPhase + "Duration"] / 60000) + " : 00";
};
答案 0 :(得分:1)
因为如果您将任何内容分配给不存在的变量,那么该变量将在全局范围内自动声明...除非您使用use strict
。