作用域類型對照
| 作用域類型 | 關鍵字 | 範圍 | 提升 | 暫時性死區 | 重複宣告 |
| 全域 | var/let/const (頂層) | 整個腳本/模組 | var 有、let/const 有但進入 TDZ | let/const 有 | var 允許、let/const 禁止 |
| 函式 | var/let/const | 函式內部 | 同左 | 同左 | 同左 |
| 區塊 | let/const | { } 區塊內 | 有 (進入 TDZ) | 有 | 禁止 |
| 模組 | export/import | 模組檔案 | 不適用 | 不適用 | 不適用 |
var:函式作用域與提升
var global = 'global';
function scopeDemo() {
console.log(global); // undefined (非 "global"!) - 提升導致區域變數遮蔽
var global = 'local';
console.log(global); // 'local'
}
scopeDemo();
console.log(global); // 'global'
// 等同於:
function scopeDemoHoisted() {
var global; // 提升到函式頂部,值為 undefined
console.log(global);
global = 'local';
console.log(global);
}
let/const:區塊作用域與 TDZ
{
// 暫時性死區 (TDZ) 開始
// console.log(blockVar); // ReferenceError: Cannot access 'blockVar' before initialization
let blockVar = 'I am block scoped';
const BLOCK_CONST = 'constant';
// TDZ 結束
console.log(blockVar); // 正常
}
console.log(blockVar); // ReferenceError: blockVar is not defined
// 迴圈中的經典閉包問題
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 100); // 輸出 3, 3, 3
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j), 100); // 輸出 0, 1, 2 ✅
}
// let 每次迭代建立新綁定,var 只有一個共享綁定
全域物件屬性 vs 全域變數
var varGlobal = 'var';
let letGlobal = 'let';
const constGlobal = 'const';
implicitGlobal = 'implicit'; // 嚴格模式下拋錯
console.log(window.varGlobal); // 'var' (瀏覽器)
console.log(window.letGlobal); // undefined
console.log(window.constGlobal); // undefined
console.log(window.implicitGlobal); // 'implicit'
// globalThis (跨環境通用)
console.log(globalThis.varGlobal); // 'var'
作用域鏈與變數查找
const global = 'global';
function outer() {
const outerVar = 'outer';
function inner() {
const innerVar = 'inner';
console.log(global); // 找到全域
console.log(outerVar); // 向外層尋找
console.log(innerVar); // 當前作用域
}
inner();
}
outer();
// 查找順序:當前作用域 → 外層函式作用域 → ... → 全域作用域 → globalThis
// 找不到拋 ReferenceError (嚴格模式) 或建立隱含全域 (非嚴格模式)
閉包:函式記住其出生環境
// 經典閉包:計數器
function createCounter() {
let count = 0; // 自由變數
return function() {
return ++count; // 內部函式參考外部變數
};
}
const counter1 = createCounter();
const counter2 = createCounter();
console.log(counter1()); // 1
console.log(counter1()); // 2
console.log(counter2()); // 1 (獨立環境)
// 模組模式:封裝私有狀態
const CounterModule = (function() {
let count = 0;
return {
increment() { return ++count; },
decrement() { return --count; },
getCount() { return count; }
};
})();
CounterModule.increment(); // 1
CounterModule.increment(); // 2
// count 無法直接存取,被閉包保護
實務最佳實踐
- 預設使用 const:不重新指派的變數皆用 const
- 需重新指派用 let:迴圈計數器、交換值、累加器
- 禁用 var:避免提升、函式作用域、全域污染等陷阱
- 縮小作用域:在最近的 { } 區塊宣告變數
- 避免全域變數:使用 IIFE、ESM 模組、命名空間隔離
ES Modules 作用域
// a.js
export const API_URL = 'https://api.example.com';
let internalCache = {}; // 模組私有,外部不可存取
export function fetchData() { ... }
// b.js
import { API_URL, fetchData } from './a.js';
// internalCache 不可見,真正的模組作用域隔離
常見錯誤與除錯
| 錯誤 | 原因 | 修正 |
| ReferenceError: x is not defined | 變數未宣告或在 TDZ 中存取 | 檢查宣告位置、拼字、作用域範圍 |
| TypeError: Assignment to constant variable | const 重新指派 | 改用 let 或重構邏輯 |
| 迴圈閉包輸出相同值 | var 函式作用域共享 | 改用 let 或 IIFE 包裹 |
| 全域變數衝突 | 多腳本污染 window | 使用模組、IIFE、命名空間 |
總結
JavaScript 作用域演進:var (函式作用域、提升) → let/const (區塊作用域、TDZ) → ES Modules (模組作用域)。深入理解作用域鏈、閉包、提升機制,是寫出可維護、無 Bug 程式碼的基石。