閉包 = 函式 + 該函式宣告時的詞法環境 (Lexical Environment)
當函式在其**定義時的作用域外**被執行,卻仍能存取定義時作用域內的變數,即形成閉包。
function createCounter() {
let count = 0; // 自由變數
return function() { // 內部函式
return ++count; // 參照自由變數
};
}
const counterA = createCounter();
counterA(); // 1
counterA(); // 2
const counterB = createCounter();
counterB(); // 1 (獨立狀態)
counterB(); // 2
count 變數被內部函式「閉合」保存,不隨外層函式結束而銷毀,每次呼叫 createCounter 都會建立**新的獨立詞法環境**,實現狀態封裝。
// ❌ 錯誤:var 無塊級作用域,所有回調共用同一個 i
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 100); // 輸出 4, 4, 4
}
// ✅ 修正 1:let 塊級作用域 (每次迴圈建立新綁定)
for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 100); // 1, 2, 3
}
// ✅ 修正 2:IIFE 建立獨立閉包 (ES5 寫法)
for (var i = 1; i <= 3; i++) {
(function(j) {
setTimeout(() => console.log(j), 100);
})(i); // 1, 2, 3
}
function createBankAccount(initialBalance) {
let balance = initialBalance; // 私有變數
const transactions = []; // 私有陣列
return {
// 公有方法 (特權方法)
deposit(amount) {
if (amount > 0) {
balance += amount;
transactions.push({ type: 'deposit', amount, time: Date.now() });
}
return balance;
},
withdraw(amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
transactions.push({ type: 'withdraw', amount, time: Date.now() });
}
return balance;
},
getBalance() { return balance; },
getHistory() { return [...transactions]; } // 回傳副本,防篡改
};
}
const acc = createBankAccount(1000);
acc.deposit(500); // 1500
acc.withdraw(200); // 1300
console.log(acc.balance); // undefined (無法直接存取)
console.log(acc.getHistory());
const EventBus = (function() {
const events = {}; // 私有狀態
function on(event, handler) {
(events[event] ||= []).push(handler);
}
function off(event, handler) {
if (!events[event]) return;
events[event] = events[event].filter(h => h !== handler);
}
function emit(event, ...args) {
(events[event] || []).forEach(h => h(...args));
}
return { on, off, emit }; // 公開 API
})();
EventBus.on('login', user => console.log(user, 'logged in'));
EventBus.emit('login', { name: 'Alice' });
// 柯里化:多參函式轉為單參函式鏈
const add = a => b => c => a + b + c;
add(1)(2)(3); // 6
// 部份應用:預設部分參數
const fetchWithAuth = (token) => (url, options = {}) =>
fetch(url, { ...options, headers: { ...options.headers, Authorization: `Bearer ${token}` } });
const api = fetchWithAuth("MY_TOKEN");
api("/users"); // 自動帶入 token
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const fib = memoize(n => n <= 1 ? n : fib(n-1) + fib(n-2));
fib(50); // 瞬間回傳
element.removeEventListener、clearInterval。handler = null、cache.clear()。WeakMap/WeakRef (ES2021) 實作快取,不阻礙 GC。
原生語法取代閉包模擬 Private:
class BankAccount {
#balance = 0; // 私有欄位 (硬性私有,不可從外部存取)
#transactions = [];
constructor(initial) { this.#balance = initial; }
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
this.#transactions.push({ type: 'deposit', amount });
}
}
getBalance() { return this.#balance; }
}
優點:語法原生、效能更好、不需閉包、除錯器支援。
缺點:較新語法 (需 Babel/現代環境)、無法動態增減私有成員。
#privateFields 替代閉包模擬私有成員,但理解閉包機制仍是進階 JS 開發者的必修課。