[英]Reassigning global variable in JavaScript - Can somebody explain to me why currentAcc stays undefined
所以基本上我在没有.addEventlistener() 的简单测试场景中尝试了同样的事情,它可以工作,但我没有让它工作,currentAcc 在全局scope中保持未定义并且不采用 function 的分配值。 我将非常感谢一些帮助。
let currentAcc;
function logIn() {
function logInCurrAcc(event) {
event.preventDefault();
currentAcc = accounts.find((acc) => acc.username === usernameInput.value);
console.log(currentAcc);
if (currentAcc.password === passwordInput.value) {
window.location.assign("app.html");
} else {
alert.classList.remove("hidden");
setTimeout(function () {
alert.classList.add("hidden");
}, 3000);
}
}
submitFormBtn.addEventListener("click", logInCurrAcc);
}
console.log(currentAcc);
// Initializes everything
function init() {
if (document.body.contains(tabsContainer)) {
tabsComponent();
sliderComponent();
modal();
logIn();
} else {
console.log("Not loading init");
}
}
init();```
JavaScript 解释器在执行之前不会进入 function 的主体。
这是解释器如何执行代码的简化示例:
let currentAcc; // empty variable declaration
function logIn() {} // function declaration, doesn't enter, only saves a pointer to it into the memory
console.log(currentAcc) // undefined, because `currentAcc` is still empty
function init() {} // function declaration
init() // function execution, now interpreter goes into the body of `init` func and so on
因此,根据您发布的代码, currentAcc
变量在用户单击之前保持undefined
。
如果需要在页面之间传递数据,请考虑使用window.localStorage或window.sessionStorage 。
如果您需要更多帮助,请发布一个最小的、可重现的示例,以便我可以帮助您提供一些实际代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.