作用域
一句话解释
作用域 是 区域 的 code 哪里 变量 是 accessible — 它 determines 什么 变量 你 能 see 从 given 点.
用大白话说
作用域是 设置的 规则那个 determines 哪里变量是 可见. JavaScript 有 three 主要类型: 全局作用域 (可见 everywhere), 函数作用域 (可见在内函数), and 块作用域 (可见在内 { } block).
var is function-scoped — it is visible throughout the enclosing function, even outside the block where it was declared. let and const are block-scoped — they are only visible within the nearest { } block.
Understanding scope is crucial for avoiding naming conflicts, managing variable lifetimes, and writing predictable code. Closures rely on scope: an inner function can access variables from its outer scope even after the outer function returns.
示例
javascript
function demo() {
let blockScoped = "inside block";
if (true) {
let inner = "only here";
console.log(blockScoped); // OK
}
// console.log(inner); // ReferenceError
}blockScoped 是 可见 贯穿 函数. 内部 是 仅 可见 内部 如果 块.
相关术语
相关资源
相关课程
- 变量
学习 关于 作用域.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。