**將「橫切關注點」(Cross-cutting Concerns) 從業務邏輯中剝離,以「切面」動態織入。**
典型橫切關注點:日誌、性能統計、權限驗證、參數轉換、錯誤處理、緩存、事務、埋點。
Function.prototype.before = function(beforeFn) {
const self = this;
return function(...args) {
const ret = beforeFn.apply(this, args);
if (ret === false) return ret; // 攔截:返回 false 阻斷後續
return self.apply(this, args);
};
};
Function.prototype.after = function(afterFn) {
const self = this;
return function(...args) {
const ret = self.apply(this, args);
afterFn.apply(this, args);
return ret;
};
};
// 舊代碼
window.onload = initA;
// 新代碼:不改動舊代碼,動態裝飾
window.onload = (window.onload || (() => {})).after(initB);
// 或
window.onload = (window.onload || (() => {})).before(initB); // 前置也可
Function.prototype.profile = function(label) {
return this.before(() => {
this._t0 = performance.now();
}).after(() => {
console.log(`[Profile] ${label}: ${(performance.now() - this._t0).toFixed(2)}ms`);
});
};
// 使用:任何函數一鍵加上性能統計
const heavy = function() { /* ... */ }.profile('heavy');
heavy(); // 控制台輸出耗時
const validators = {
required: v => v ? true : '必填',
email: v => /^[^@]+@[^@]+\.[^@]+$/.test(v) || '郵箱格式錯誤',
minLen: (n) => v => v.length >= n || `至少 ${n} 字元`
};
function validate(rules) {
return function(data) {
for (const [field, rule] of Object.entries(rules)) {
const err = rule(data[field]);
if (err !== true) { alert(err); return false; } // 返回 false 截斷
}
};
}
const submit = function(data) { api.post('/submit', data); };
const validatedSubmit = submit.before(validate({ email: validators.email, password: validators.minLen(8) }));
validatedSubmit({ email: 'a@b.com', password: '12345678' }); // 通過
validatedSubmit({ email: 'bad', password: '123' }); // 彈窗攔截,submit 不執行
const request = (options) => fetch(options.url, { method: 'POST', body: JSON.stringify(options.data) });
const withAuth = request.before(options => {
options.data = { ...options.data, token: getToken(), timestamp: Date.now() };
});
const withJsonp = request.before(options => {
if (options.jsonp) options.data.callback = 'cb_' + Date.now();
});
withAuth({ url: '/api/a', data: { a: 1 } }); // 自動帶 token
withJsonp({ url: '/api/b', data: { b: 2 }, jsonp: true }); // 自動帶 callback
// 修改 after:返回非 undefined 即終止鏈路
Function.prototype.after = function(afterFn) {
const self = this;
return function(...args) {
const ret = self.apply(this, args);
if (ret !== undefined) return ret; // 有返回值 → 終止
return afterFn.apply(this, args);
};
};
const uploadPlugin = () => { if (hasPlugin) return initPlugin(); };
const uploadHtml5 = () => { if (supportHtml5) return initHtml5(); };
const uploadFlash = () => { if (supportFlash) return initFlash(); };
const uploadForm = () => initForm(); // 最後兜底
const upload = uploadPlugin
.after(uploadHtml5)
.after(uploadFlash)
.after(uploadForm);
upload(); // 自動選擇最高優先級可用方式
// 需屏蔽 Flash:只需移除一行 .after(uploadFlash) 即可,零侵入
// 傳統繼承
class BaseUpload { start() { /* ... */ } }
class PluginUpload extends BaseUpload { start() { scan(); super.start(); } }
// 組合:裝飾器模式
const baseStart = function() { /* 核心上傳邏輯 */ };
const withScan = baseStart.before(() => scanFiles()); // 動態組合
const withRetry = baseStart.after((...args) => { if (failed) retry(args); });
// 同一個基礎函數,靈活組合出 N 種變體,無需建立 N 個子類
| 框架 | AOP 實現 | 典型用例 |
|---|---|---|
| Express/Koa | 中間件 | 日誌、認證、錯誤處理、限流 |
| NestJS | Interceptor / Guard / Pipe / Filter | 響應轉換、權限、驗證、異常捕獲 |
| Spring (Java) | @AspectJ / Proxy | 事務、緩存、安全、監控 |
| Aspect.js / kaop-ts | TypeScript 裝飾器 + 代理 | 前端類 Spring AOP 體驗 |
| RxJS | Operator (pipe) | 重試、去抖、緩存、日誌、錯誤恢復 |
AOP 在 JavaScript 中極其輕量:`before`/`after` 兩個原型方法即可構建強大的切面體系。**核心價值在於「不修改原函數」即可橫向擴展能力**,完美符合開閉原則。從防止 `onload` 覆蓋到職責鏈上傳選擇,從性能剖析到組合替代繼承,掌握 AOP 思維能讓代碼更乾淨、更可測試、更易演進。