我正在制作一个具有两个阶段的计时器,但我忘记了在给计时器对象的函数中初始化一些变量。但是它似乎没有问题。
例如,使用timerObj.startTime,我知道我将其添加到对象中并在其中进行定义,然后在timerObj.start()中进行定义。但是,我没有为timerObj前缀的currentTime,minutesLeft和secondLeft仍然可以正常工作,而无需全局定义或在interval函数内定义。是否以与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";
};
最佳答案
因为如果您给不存在的变量赋值,那么除非您使用use strict
,否则该变量将在全局范围内自动声明。