作用域 and Visibility
理解变量作用域 — 全局, 函数, and 块作用域 — and 如何 visibility controls access in 你的 code.
你将学到
- 什么作用域是 and 为什么它 prevents naming conflicts
- difference 之间全局, 函数, and 块作用域
- 如何 let/const and var differ in scoping behavior
- 什么闭包是 and 如何它们 capture 作用域
- 最佳实践 for keeping 作用域 as narrow as 可能
概念讲解
Scope and Visibility
Scope 是 the region of your program where a variable is accessible. It determines where a name is valid and where it is not. Scope is a protective mechanism: it prevents variables from colliding with each other and keeps the program organized by limiting where each name has meaning.
Three Levels of Scope
JavaScript has three main levels of scope:
- Global scope — variables declared outside any function or block. They are accessible everywhere, which sounds convenient but is dangerous: any part of the program can change them, making bugs hard to trace.
- Function scope — variables declared inside a function. They exist only within that function and are destroyed when it returns. This is the natural boundary for most variables.
- Block scope — variables declared with
letorconstinside a block ({}). They exist only within that block. A block can be an如果body, aforloop, or any pair of braces.
const global = "I am everywhere";
function example() {
const functionScoped = "I exist only in example()";
if (true) {
const blockScoped = "I exist only in this if-block";
console.log(global, functionScoped, blockScoped); // all accessible
}
// console.log(blockScoped); // ReferenceError — out of scope
}
let/const vs. var
The older var keyword has function scope, not block scope. A var declared inside an 如果 block leaks out to the entire function. This is a major source of bugs, which is why modern JavaScript uses let and const exclusively — both are block-scoped and behave predictably.
function demo() {
if (true) {
var oldWay = "leaks out"; // function-scoped
let newWay = "stays in"; // block-scoped
}
console.log(oldWay); // "leaks out" — var ignored the block
// console.log(newWay); // ReferenceError — let respected the block
}
Closures
A closure is a function that "remembers" the scope where it was created, even after that scope has finished executing. This is how you create private data and stateful functions in JavaScript:
function makeCounter() {
let count = 0; // private — only accessible via the returned function
return function () {
count++;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2 — the count variable persists
Keep Scope Narrow
A general principle: declare variables in the narrowest scope that works. If a variable is only needed inside a loop, declare it inside the loop. If it is only needed in an 如果 block, declare it there. Narrow scope reduces naming conflicts, makes variables easier to reason about, and helps the compiler optimize. Global variables should be rare and intentional — each one is a potential source of subtle bugs.
示例代码
// Demonstrate all three scope levels
const appName = "MyApp"; // global scope
function createUser(name) {
const userId = Math.floor(Math.random() * 1000); // function scope
// Block scope inside a conditional
if (name.length > 0) {
const displayName = name.trim(); // block scope
console.log(`Creating ${displayName} for ${appName}`);
}
// displayName is not accessible here — it was block-scoped
return { id: userId, name: name };
}
// Closure: a function factory that captures private state
function makeAccount(initialBalance) {
let balance = initialBalance; // private — captured by closure
return {
deposit(amount) { balance += amount; return balance; },
withdraw(amount) {
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
return balance;
},
getBalance() { return balance; },
};
}
const account = makeAccount(100);
account.deposit(50); // balance is now 150
account.withdraw(30); // balance is now 120
console.log(account.getBalance()); // 120
// console.log(balance); // ReferenceError — balance is private
createUser 函数 shows 全局, 函数, and 块作用域. makeAccount factory uses 闭包到 keep balance 私有 — 它能 仅是 accessed 通过 deposit, withdraw, and getBalance 方法.
动手试一试
- JSON Formatter
JSON 结构 mirrors 作用域: nested 对象创建 nested visibility. See 如何数据是 组织 hierarchically.
- Code Minifier
Minifiers rename 变量到 短 names 在内它们的作用域 — practical demonstration 的作用域边界.
常见错误
错误写法
Using var 相反的 let/const, causing 变量到 leak out 的块.
正确做法
总是 use let (for reassignable) or const (for fixed) 相反的 var. var 有 confusing 函数-scoping 那个 leads 到 bugs. Modern code 应该从不 use var.
错误写法
Declaring 所有变量 at 顶部的 函数 '只是 in 情况'.
正确做法
Declare 变量哪里它们是 首先需要, in narrowest 作用域. 这个制作它们 easier 到查找, reduces 它们的 lifetime, and prevents accidental use 之前 initialization.
错误写法
创建全局变量不使用 realizing 它 (forgetting let/const).
正确做法
总是 use let or const. 编写 x = 5 不使用 keyword 创建全局变量 in 非-strict 模式. 启用 'use strict' 到 catch 这个 mistake as 错误.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for scoping 规则, var 对比 let 对比 const, and 闭包模式.
练习 作用域 and Visibility
8 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。