「支援函數」≠「函數式語言」。真正的函數式語言要求函數具備三大特性:**一級公民 (First-class)、閉包捕獲狀態、無副作用 (Referential Transparency)**。JavaScript 同時擁有這三特性,但也允許破壞它們的寫法,需開發者自律。
函數可作為:變數賦值、參數傳遞、回傳值、資料結構元素。
// 1. 賦值給變數
const greet = name => `Hello, ${name}`;
// 2. 作為參數傳遞 (高階函數)
const applyTwice = (fn, x) => fn(fn(x));
console.log(applyTwice(x => x * 2, 3)); // 12
// 3. 作為回傳值 (柯里化/工廠函數)
const createMultiplier = factor => x => x * factor;
const double = createMultiplier(2);
console.log(double(5)); // 10
// 4. 存入資料結構
const handlers = {
GET: handleGet,
POST: handlePost
};
const handler = handlers[req.method];
Function 物件,天然一級公民。函數定義時捕獲外層詞法環境的變數,形成閉包。外層函數執行結束後,內部函數仍保有對捕獲變數的引用。
// 經典計數器閉包
function createCounter() {
let count = 0; // 私有狀態,外部無法直接存取
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
}
const counterA = createCounter();
const counterB = createCounter();
counterA.increment(); // 1
counterA.increment(); // 2
counterB.increment(); // 1 (獨立狀態)
console.log(counterA.getValue()); // 2
console.log(counterB.getValue()); // 1
function Person(name) {
let _name = name; // 私有欄位
this.getName = () => _name;
this.setName = n => { _name = n; };
// 方法也可存取私有狀態
this.greet = () => console.log(`Hi, I'm ${_name}`);
}
const p1 = new Person('Alice');
const p2 = new Person('Bob');
p1.greet(); // Hi, I'm Alice
p2.greet(); // Hi, I'm Bob
// p1._name // undefined (外部無法存取)
純函數:相同輸入必得相同輸出,不修改外部狀態,不依賴外部可變狀態。
// 純函數
const add = (a, b) => a + b;
const map = (arr, fn) => arr.map(fn); // 不修改原陣列
// 非純函數 (有副作用)
let total = 0;
const addToTotal = x => { total += x; return total; }; // 修改外部變數
const pushItem = (arr, item) => { arr.push(item); return arr; } // 修改輸入參數
const random = () => Math.random(); // 依賴外部狀態 (隨機種子)
const log = x => { console.log(x); return x; } // I/O 副作用
this 指向不穩定導致隱性依賴// ❌ 非純
function processUsers(users) {
users.forEach(u => u.processed = true); // 突變輸入
return users.filter(u => u.active);
}
// ✅ 純函數版
const processUsers = users =>
users
.filter(u => u.active)
.map(u => ({ ...u, processed: true })); // 產生新物件
// 使用 Object.freeze 凍結資料結構防禦性防止突變
const frozenUsers = Object.freeze(users.map(u => Object.freeze({...u})));
現實應用中,核心業務邏輯 (計算、轉換、驗證) 用純函數,邊界層 (I/O、DOM、狀態管理) 隔離副作用。
// Redux 架構範例
// 1. Reducer (純函數) - 核心邏輯
const userReducer = (state, action) => {
switch (action.type) {
case 'SET_NAME': return { ...state, name: action.payload };
default: return state;
}
};
// 2. Store - 狀態容器 (副作用邊界)
// 3. Middleware (thunk/saga) - 非同步副作用集中處理
// 4. UI 元件 - 觸發 action、訂閱 state 變化
| 特性 | JS 支援度 | 破壞方式 | 最佳實踐 |
|---|---|---|---|
| 一級公民 | ✅ 完整 | 濫用全域函數污染命名空間 | 模組化、IIFE、ES Modules |
| 閉包/狀態捕獲 | ✅ 完整 | 迴圈中 var 共用變數、記憶體洩漏 (未釋放大物件引用) | let/const 區塊作用域、WeakMap 緩存 |
| 無副作用 | ⚠️ 需自律 | 隨意突變參數、全域狀態、I/O 混雜邏輯 | 核心純函數、副作用邊界化、Immer/Immutable.js |