AOP 在 Java 世界無人不知,在 JavaScript 裡卻常被忽略。其實只要一個 before 和一個 after 包裝器,就能解決很多惱人的結構問題。以下用六個實際案例說明。
顧名思義,before 讓新函式在原函式之前執行,after 則在之後執行。關鍵設計是讓它們共用 this 與 arguments,這樣包裝後的函式行為才和原本一致:
Function.prototype.before = function (beforeFn) {
const self = this;
return function () {
// 前一個回傳 false 就中斷,不執行原函式
if (beforeFn.apply(this, arguments) === false) return;
return self.apply(this, arguments);
};
};
Function.prototype.after = function (afterFn) {
const self = this;
return function () {
const result = self.apply(this, arguments);
// 回傳非 undefined 時以新值取代(用於責任鏈)
return afterFn.apply(this, arguments) === undefined ? result : undefined;
};
};
最原始的解法是直接把新程式塞進原本的 window.onload 裡,侵入性最強。稍微好一點的做法是用中間變數保存舊函式:
const originalOnload = window.onload;
window.onload = function () {
originalOnload && originalOnload();
// 新程式
};
但這多了一個需要維護的 originalOnload。用 after 就完全不必碰原函式:
window.onload = (function () {
// 原本的 onload 內容
}).after(function () {
// 想追加的程式
});
就像天冷時人會加一件外套,而不是把自己的皮換掉——動態裝飾的好處就是零侵入。
跟業務無關的統計程式硬插進函式裡,向來令人不悅。比如要統計「建立一千個節點」耗時多久:
const measure = function () {
const start = performance.now();
this(); // 執行被包裝的函式
console.log('耗時', performance.now() - start, 'ms');
};
const createNodes = function () {
const frag = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) frag.appendChild(document.createElement('div'));
document.body.appendChild(frag);
}.after(measure); // 只要一行
createNodes();
從此任何函式都能一行加上計時,而原函式完全不必改動。
最糟的寫法是把所有驗證都塞進 send 裡。改成策略集合會好得多:
const validators = {
notEmpty: v => v.trim() !== '' || '內容不可空白',
isEmail: v => /^[^@]+@[^@]+\.[^@]+$/.test(v) || '格式不正確'
};
function validate(rules, value) {
for (const rule of rules) {
const msg = validators[rule](value);
if (msg !== true) return msg;
}
return true;
}
接著用 before 把校驗與送出徹底分離,做成真正即插即用的形式:
const send = function () {
console.log('送出:', this.value);
}.before(function () {
// 回傳 false 就會阻斷 send 的執行
const result = validate(['notEmpty', 'isEmail'], this.value);
if (result !== true) alert(result);
return result === true;
});
因為 before 與原函式共用 this 與 arguments,this.value 能自然傳到校驗函式裡,不必多寫任何轉接程式。
專案裡常用 retype=jsonp 或 retype=iframe 區分跨域請求方式,除此之外兩者的參數完全相同。與其把分支寫進請求函式,不如讓它保持單一職責:
const request = function (options) {
console.log('發送', options); // 只負責發送,不關心型別
};
request = request.before(function (options) {
options.retype = this.type; // 由呼叫端決定
});
request.call({ type: 'jsonp' }, { url: '/api/data' });
請求函式裡沒有任何 if 分支,型別資訊由外部注入。這是「控制反轉」的迷你版。
某個上傳功能提供「外掛控制項、HTML5、Flash、表單」四種方式,需依優先級與瀏覽器支援度挑一種。傳統寫法是一串 if-else 加提前 return,日子久了誰也不敢動。改成責任鏈後:
// 先讓 after 支援「回傳值即中斷」
Function.prototype.after = function (afterFn) {
const self = this;
return function () {
const result = self.apply(this, arguments);
const next = afterFn.apply(this, arguments);
return next !== undefined ? next : result; // 回傳非 undefined 就中斷鏈
};
};
const usePlugin = function () {
if (hasPlugin) return createPluginUpload();
};
const useHtml5 = function () {
if (hasHtml5) return createHtml5Upload();
};
const useFlash = function () {
if (hasFlash) return createFlashUpload();
};
const useForm = function () { return createFormUpload(); };
const upload = usePlugin.after(useHtml5).after(useFlash).after(useForm);
upload();
要停用 Flash,只需從鏈上移除那一行,不必碰任何判斷邏輯。事件冒泡就是這個模式最熟悉的例子。
設計上傳類別時,若 PluginUpload 繼承 Upload 再覆寫 start_upload,只為了在中途插入「檔案掃描」這一步,那麼繼承帶來的耦合其實並不划算。改用裝飾:
const scanBefore = function () {
console.log('開始掃描檔案…');
};
// 不需要額外衍生子類,直接裝飾原方法
pluginUpload.start_upload = Upload.prototype.start_upload.before(scanBefore);
組合更輕、更靈活,也不必為了插入一個步驟而複製整條繼承鏈。
這六個場景背後是同一件事:辨識出橫切關注點,並用裝飾把它從主流程裡移出去。程式的可讀性、可測試性與可替換性都因此提升。值得注意的是,ES decorators 已在近年進入標準流程,@log、@measure 這類寫法未來會比手工包裝更直觀;但手工版的 before/after 只有十幾行、零依賴,理解它仍有實際意義。