JavaScript 函数采用“词法作用域”,即:函数内部定义的变量只能在该函数及其子函数中访问。函数外部定义的变量可以从其内部函数访问。作用域链决定了查找变量的顺序,沿着作用域链逐级向上查找。

JavaScript 中的函数作用域
JavaScript 采用“词法作用域”,这意味着函数作用域由函数的文本位置决定。
函数作用域的含义:
作用域链:
当 JavaScript 运行函数时,它会创建一个包含该函数及其父函数作用域的“作用域链”。每次查找变量时,JavaScript 都会沿着作用域链逐级向上查找,直到找到该变量。
示例:
<code class="javascript">const globalVar = "global";
function outer() {
const outerVar = "outer";
function inner() {
const innerVar = "inner";
console.log(globalVar, outerVar, innerVar); // 输出: "global" "outer" "inner"
}
inner();
console.log(globalVar, outerVar); // 输出: "global" "outer"
}
outer();
console.log(globalVar); // 输出: "global"</code>在上述示例中:
globalVar 在全局作用域中定义,所有函数都可以访问它。outerVar 在 outer() 函数中定义,outer() 函数及其子函数 inner() 可以访问它。innerVar 在 inner() 函数中定义,只能在 inner() 函数中访问。注意:
let 和 const 定义的变量仅在其声明的代码块中可见。以上就是js中什么是函数作用域的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号