JavaScript 最大特色之一是「函式也是一等公民」——函式可像物件一樣被指派、傳遞、儲存。加上 JS 不強制型別檢查,陣列可存放任意型別資料,自然也能存放函式。本文示範如何建構函式陣列並實作簡易指令隊列。
<!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函式陣列是 JS 函數式程式設計的基石,廣泛應用於中介軟體、事件總線、動畫隊列、狀態機等場景。掌握此技巧能讓程式碼更具組合性與彈性。