解释 JavaScript 中的提升
提升允许我们在函数和变量 (使用 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">CLICK HERE</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>
输出
上述代码将生成以下输出 −
点击“点击此处”按钮 −
广告