作用域
一句话解释
作用域是 区域的 你的 program 哪里变量是 可见 and 能是 used.
用大白话说
Scope decides where a variable "lives" and where you are allowed to reference it. A variable declared inside a function is not visible outside that function — its scope is local. A variable declared at the top level of the file is global and visible everywhere.
Scope prevents naming collisions. You can have a variable called i inside one function and another i inside a different function, and they will not interfere with each other because each has its own local scope.
Most modern languages use lexical (static) scope — the scope is determined by where the variable is written in the source code, not by where the function is called. Block scope (introduced by let and const in JavaScript) confines a variable to the nearest curly-brace block.
示例
// Global scope — visible everywhere
var globalVar = "I am global";
function outer() {
// Function scope — visible only inside outer()
var functionVar = "I am function-scoped";
if (true) {
// Block scope — visible only inside this block
let blockVar = "I am block-scoped";
console.log(globalVar, functionVar, blockVar); // ✅ all accessible
}
console.log(blockVar); // ❌ ReferenceError: blockVar is not defined
}
outer();
console.log(functionVar); // ❌ ReferenceError: functionVar is not defined展示了三种作用域层级:globalVar 全局可访问,functionVar 仅在 outer() 函数内可访问,blockVar 仅在 if 块内可访问。在作用域外访问会抛出 ReferenceError。
工作原理
- Global scope — variables declared outside any function or block; visible everywhere.
- Function scope — variables declared inside a function; visible only within that function.
- Block scope — variables declared with
let/constinside{}; visible only in that block. - When code references a variable, the interpreter searches the current scope, then outer scopes, up to global.
常见混淆
容易混淆的对象: 上下文
关键区别: 作用域是 关于哪个变量是 可见 (编译-时间概念); 上下文是 关于什么
这个refers 到 at 运行时. 它们是 related 但 distinct.
相关术语
相关资源
相关课程
- 变量
作用域是 introduced alongside 变量
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。