萬盛學電腦網

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

JavaScript 實作函式陣列:函式即資料的靈活運用

JavaScript 最大特色之一是「函式也是一等公民」——函式可像物件一樣被指派、傳遞、儲存。加上 JS 不強制型別檢查,陣列可存放任意型別資料,自然也能存放函式。本文示範如何建構函式陣列並實作簡易指令隊列。

核心概念

  • 函式可指派給變數、作為參數傳遞、作為回傳值、存入陣列/物件
  • 陣列元素型別不限,可混合存放函式、字串、數字、物件
  • 透過陣列方法(push、pop、shift、forEach)操作函式隊列

實作範例:可撤銷的指令隊列

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Function Array Demo</title>
</head>
<body>
    <input type="button" value="執行並示範 Undo" onclick="runDemo()" />
    <script>
        const commandQueue = [];

        // 定義可記錄自身的函式
        const action1 = function(flag) {
            console.log('動作 1 執行');
            if (flag) commandQueue.push(action1);
        };

        const action2 = function(flag) {
            console.log('動作 2 執行');
            if (flag) commandQueue.push(action2);
        };

        const action3 = function(flag) {
            console.log('動作 3 執行');
            if (flag) commandQueue.push(action3);
        };

        function runDemo() {
            // 執行並記錄
            action1(true);
            action2(true);
            action3(true);
            
            console.log('--- 目前隊列長度:', commandQueue.length); // 3
            
            // 模擬 Undo:移除最後一個並執行剩餘
            const undone = commandQueue.pop();
            console.log('--- Undo 移除:', undone.name);
            
            // 重新執行剩餘隊列
            commandQueue.forEach(fn => fn(false)); // false 避免重複記錄
        }
    </script>
</body>
</html>

進階應用:命令模式

將函式封裝為命令物件,支援 undo/redo、延遲執行、批次處理:

class Command {
    constructor(executeFn, undoFn) {
        this.execute = executeFn;
        this.undo = undoFn;
    }
}

const history = [];
const redoStack = [];

function executeCommand(cmd) {
    cmd.execute();
    history.push(cmd);
    redoStack.length = 0; // 新指令清空 redo
}

function undo() {
    const cmd = history.pop();
    if (cmd) {
        cmd.undo();
        redoStack.push(cmd);
    }
}

function redo() {
    const cmd = redoStack.pop();
    if (cmd) {
        cmd.execute();
        history.push(cmd);
    }
}

// 使用範例
const textArea = document.getElementById('editor');
executeCommand(new Command(
    () => textArea.value += 'Hello ',
    () => textArea.value = textArea.value.slice(0, -6)
));

注意事項

  • 閉包捕捉變數時注意作用域,必要時用 bind 或箭頭函式固定 this
  • 長期運行的應用需限制隊列長度,避免記憶體洩漏
  • 序列化函式陣列需自行實作(函式本身無法直接 JSON.stringify)

總結

函式陣列是 JS 函數式程式設計的基石,廣泛應用於中介軟體、事件總線、動畫隊列、狀態機等場景。掌握此技巧能讓程式碼更具組合性與彈性。

copyright © 萬盛學電腦網 all rights reserved