萬盛學電腦網

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

JavaScript AOP 實戰:用「切面」解耦橫切關注點(日誌、驗證、參數裝飾、職責鏈、組合替代繼承)

AOP 核心思想

**將「橫切關注點」(Cross-cutting Concerns) 從業務邏輯中剝離,以「切面」動態織入。**

典型橫切關注點:日誌、性能統計、權限驗證、參數轉換、錯誤處理、緩存、事務、埋點。

基礎設施:`Function.prototype.before` / `after`

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

六大實戰場景

1. 防止 `window.onload` 被覆蓋 (後置切面)

// 舊代碼
window.onload = initA;

// 新代碼:不改動舊代碼,動態裝飾
window.onload = (window.onload || (() => {})).after(initB);
// 或
window.onload = (window.onload || (() => {})).before(initB); // 前置也可

2. 無侵入性能統計 (環繞切面:before + after)

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(); // 控制台輸出耗時

3. 表單驗證與提交分離 (前置切面攔截)

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 不執行

4. AJAX 參數動態裝飾 (前置切面注入公共參數)

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

5. 職責鏈模式:上傳方式自動選擇 (優先級鏈)

// 修改 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) 即可,零侵入

6. 組合替代繼承:動態擴展功能而非建立子類

// 傳統繼承
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 實踐

框架AOP 實現典型用例
Express/Koa中間件日誌、認證、錯誤處理、限流
NestJSInterceptor / Guard / Pipe / Filter響應轉換、權限、驗證、異常捕獲
Spring (Java)@AspectJ / Proxy事務、緩存、安全、監控
Aspect.js / kaop-tsTypeScript 裝飾器 + 代理前端類 Spring AOP 體驗
RxJSOperator (pipe)重試、去抖、緩存、日誌、錯誤恢復

結語

AOP 在 JavaScript 中極其輕量:`before`/`after` 兩個原型方法即可構建強大的切面體系。**核心價值在於「不修改原函數」即可橫向擴展能力**,完美符合開閉原則。從防止 `onload` 覆蓋到職責鏈上傳選擇,從性能剖析到組合替代繼承,掌握 AOP 思維能讓代碼更乾淨、更可測試、更易演進。

copyright © 萬盛學電腦網 all rights reserved