gpt4 book ai didi

javascript - 为什么我的未初始化变量可以工作?

转载 作者:行者123 更新时间:2023-12-03 02:13:23 26 4
gpt4 key购买 nike

我正在制作一个具有两个阶段的计时器,但我忘记初始化我提供给计时器对象的函数中的一些变量。但它似乎工作起来没有任何问题。

例如,对于timerObj.startTime,我知道我将其添加到对象中并在那里定义它,然后在timerObj.start()内定义它。然而,我没有以timerObj为前缀的currentTime、minesLeft和secondLeft仍然可以完全正常工作,而无需全局定义或在间隔函数内定义。它们的处理方式与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

关于javascript - 为什么我的未初始化变量可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com