萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 高階函數深度解析:從入門到實戰

什麼是高階函數?

在 JavaScript 中,函數是一等公民——它們可以像變量一樣被賦值、傳遞、返回。高階函數滿足以下任一條件:

  1. 接收一個或多個函數作為參數
  2. 返回一個函數作為結果

類型一:參數為函數(回調模式)

// 基礎範例:執行傳入的函數
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

類型三:實際應用三大支柱

1. 回調函數 - 異步控制流

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)
);

2. 事件監聽器 - DOM 交互

// addEventListener 第二個參數就是高階函數
document.getElementById('btn').addEventListener('click', function(event) {
    console.log('按鈕被點擊', event.clientX, event.clientY);
});

3. 函數組合 - 管道操作

// 組合多個函數:從右到左執行
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 事件,還是構建可復用的工具庫,理解並善用高階函數都能讓代碼更簡潔、更具表達力、更易維護。

copyright © 萬盛學電腦網 all rights reserved