解释 JavaScript 中的提升

javascriptweb developmentobject oriented programming

提升允许我们在定义函数和变量(用 var 声明)之前调用它们,方法是在代码执行开始之前将它们移动到其范围的顶部。

以下是显示 JavaScript 中变量和函数提升的代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Hoisting in JavaScript</h1>
<div class="sample">
Calling functions and variables before they are defined
</div>
<div style="color: green;" class="result"></div>
<button class="btn">点击此处</button>
<h3>
Click on the above button to see hoisting in action
</h3>
<script>
   let btnEle = document.querySelector(".btn");
   let resEle = document.querySelector(".result");
   btnEle.addEventListener("click", () => {
      resEle.innerHTML = "retString() : " + retString() + "<br>";
      resEle.innerHTML += "var a = " + a + "<br>";
      try {
         resEle.innerHTML += "let b = " + b + "<br>";
      }
      catch (err) {
         resEle.innerHTML += err;
      }
      let b = 55;
      var a = 22;
      function retString() {
         return "Hello world";
      }
   });
</script>
</body>
</html>

输出

上述代码将产生以下输出 −

点击‘CLICK HERE’按钮 −


相关文章