| 類型 | 關鍵字 | 範圍 | 提升行為 | 暫時性死區 (TDZ) |
|---|---|---|---|---|
| 全域 | var/let/const (最外層) | 整個腳本/模組 | var 初始化為 undefined;let/const 進入 TDZ | let/const 有 |
| 函數 | var/let/const (函數內) | 函數內部 | 同上 | let/const 有 |
| 區塊 | let/const/class (大括號 {}) | 最近的 { } 區塊 | 不提升(進入 TDZ) | 有 |
console.log(a); // undefined (非 ReferenceError)
var a = 1;
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 2;
foo(); // "Hello" — 函數宣告整體提升
function foo() { console.log('Hello'); }
bar(); // TypeError: bar is not a function — 函數表達式只提升變數
var bar = function() { console.log('World'); };
內層作用域可存取外層變數( léxico scope 靜態作用域)。查找順序:**當前作用域 → 外層函數/區塊 → 全域 → 未宣告拋 ReferenceError**。
// var:共用同一個 i
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 100); // 輸出 3,3,3
}
// let:每輪迴圈建立新綁定
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log('let:', i), 100); // 輸出 0,1,2
}
<script type="module"> 或 import/export 檔案擁有**獨立頂層作用域**,不污染全域 window。var 在模組頂層**不**會掛在 window 上。const**,需重新指派改 let,禁用 var。{} 區塊內宣告變數。'use strict' 捕獲隱性全域變數賦值。理解「函數作用域 (var)」與「區塊作用域 (let/const)」、提升機制、TDZ、閉包捕獲差異,是寫出無 Bug、可維護 JavaScript 程式碼的基石。