簡體   English   中英

在 JavaScript 中重新分配全局變量 - 有人可以向我解釋為什么 currentAcc 保持未定義

[英]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.localStoragewindow.sessionStorage

如果您需要更多幫助,請發布一個最小的、可重現的示例,以便我可以幫助您提供一些實際代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM