在 JavaScript 中,函數是一等公民——它們可以像變量一樣被賦值、傳遞、返回。高階函數滿足以下任一條件:
// 基礎範例:執行傳入的函數
function executeCallback(fn) {
if (typeof fn === 'function') {
fn(); // 執行回調
}
}
executeCallback(function() {
console.log("我是匿名回調函數");
});
JS 內建的 sort、filter、map、forEach 都是高階函數:
const numbers = [5, 2, 9, 1, 5, 6];
// 排序:傳入比較函數
numbers.sort((a, b) => a - b); // [1, 2, 5, 5, 6, 9]
// 篩選:傳入判斷函數
const evens = numbers.filter(n => n % 2 === 0); // [2, 6]
// 轉換:傳入映射函數
const doubled = numbers.map(n => n * 2); // [10, 4, 18, 2, 10, 12]
// 簡單工廠:根據類型返回不同處理函數
function createAdder(type) {
if (type === 'string') {
return (a, b) => String(a) + String(b); // 字串拼接
}
return (a, b) => Number(a) + Number(b); // 數值相加
}
const addStr = createAdder('string');
const addNum = createAdder('number');
console.log(addStr('1', '2')); // "12"
console.log(addNum('1', '2')); // 3
// 柯里化:將多參數函數轉為單參數鏈式調用
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return (...more) => curried(...args, ...more);
};
}
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6
console.log(curriedAdd(1)(2, 3)); // 6
function fetchData(url, onSuccess, onError) {
// 模擬異步請求
setTimeout(() => {
const success = Math.random() > 0.3;
if (success) onSuccess({ data: "用戶資料" });
else onError(new Error("網絡異常"));
}, 1000);
}
fetchData("/api/user",
(res) => console.log("成功:", res),
(err) => console.error("失敗:", err)
);
// addEventListener 第二個參數就是高階函數
document.getElementById('btn').addEventListener('click', function(event) {
console.log('按鈕被點擊', event.clientX, event.clientY);
});
// 組合多個函數:從右到左執行
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const trim = s => s.trim();
const toLower = s => s.toLowerCase();
const wrap = s => `[${s}]`;
const process = compose(wrap, toLower, trim);
console.log(process(" Hello World ")); // "[hello world]"
users.filter(isActive).map(getName) 比迴圈直觀高階函數是 JavaScript 函數式編程的基石。無論你是使用內建數組方法、編寫異步邏輯、處理 DOM 事件,還是構建可復用的工具庫,理解並善用高階函數都能讓代碼更簡潔、更具表達力、更易維護。