JS函数变量看不到全局变量

JS Function variables not seeing global variables

let numFlag = document.getElementById("numBTN-Flag");
let callFlag = document.getElementById("callScreen");
let callDisplay = document.querySelector(".numberCalling");
let callingText = document.querySelector(".connectText");

function callCancel() {
  callFlag.style.display = "none";
  numFlag.style.display = "block";
  callDisplay.innerText = "";
  display.innerText = "";
}

const answerNumber = () => {
  numFlag.style.display = "none";
  callFlag.style.display = "block";
  let callDisplay = document.querySelector(".numberCalling");
  callDisplay = callDisplay.innerText += display.innerText;
  const callText = () => {
    if (callDisplay.length >= 9) {
      let callingText = document.querySelector(".connectText");
      callingText = callingText.innerText = "łączę...";
      setTimeout(function() {
        let callingText = document.querySelector(".connectText");

        callingText = callingText.innerText = "Trwa połączenie...";
        // do zrobienia odliczanie
      }, 4000);
    } else {
      let callDisplay = document.querySelector(".numberCalling");
      callDisplay.innerText = "Zły numer";
    }
  };
  callText();
};

我运行在编写个人项目时遇到了一些小问题。这是一个小型 phone 模拟器,此刻我面临着“全局范围”问题的挑战。正如您在提供的代码中看到的那样,我在全局中有 4 个变量,但只有两个(numFlag & callFlag)可以正常工作。当涉及到 callDisplaycallingText 变量时,我每次都必须在需要时调用它们,就像函数无法访问它们一样全球版本。我尝试删除本地范围版本并希望它能在全球范围内运行,但它不会。我知道我现在可以这样离开它(它应该像它应该的那样工作)但是额外的变量只会让代码更难阅读和维护......这让我发疯,为什么它不起作用。所以请赐教:)

发生这种情况是因为以下几行

callDisplay = callDisplay.innerText += display.innerText;
callingText = callingText.innerText = "łączę...";
callingText = callingText.innerText = "Trwa połączenie...";

他们正在覆盖 callDisplaycallingText 变量。


使用

callDisplay.innerText += display.innerText;
callingText.innerText = "łączę...";
callingText.innerText = "Trwa połączenie...";

相反,它会如你所愿


let numFlag = document.getElementById("numBTN-Flag");
let callFlag = document.getElementById("callScreen");
let callDisplay = document.querySelector(".numberCalling");
let callingText = document.querySelector(".connectText");

function callCancel() {
  callFlag.style.display = "none";
  numFlag.style.display = "block";
  callDisplay.innerText = "";
  display.innerText = "";
}

const answerNumber = () => {
  numFlag.style.display = "none";
  callFlag.style.display = "block";
  callDisplay.innerText += display.innerText;

  const callText = () => {
    if (callDisplay.innerText.length >= 9) {
      callingText.innerText = "łączę...";
      setTimeout(function() {
        callingText.innerText = "Trwa połączenie...";
        // do zrobienia odliczanie
      }, 4000);
    } else {
      callDisplay.innerText = "Zły numer";
    }
  };
  callText();
};