萬盛學電腦網

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

JavaScript AOP 面向切面編程實現:before/after/around 攔截器模式

AOP 核心概念

**切面 (Aspect)**:橫切關注點(日誌、計時、權限、事務)。
**切點 (Pointcut)**:目標函數調用位置。
**通知 (Advice)**:before (前)、after (後)、around (環繞)。

輕量 AOP 實現 (aop.js)

var aop = (function() {
  function cloneFn(fn) {
    return typeof fn === 'function' ? eval('[' + fn.toString() + ']')[0] : null;
  }
  return function(options) {
    if (!options || typeof options !== 'object') return;

    var context = options.context || window;
    var targetName = typeof options.target === 'function' ? options.target.name : options.target;
    var targetFn = context[targetName];
    if (!targetFn || typeof targetFn !== 'function') return;

    var original = cloneFn(targetFn); // 保存原函數源碼重建
    var before = options.before, after = options.after, around = options.around;

    context[targetName] = function() {
      var args = arguments;
      if (around) around.apply(this, args);      // 環繞前
      if (before) before.apply(this, args);      // 前置
      var result = original.apply(this, args);   // 執行原函數
      if (after) after.apply(this, args);        // 後置
      if (around) around.apply(this, args);      // 環繞後
      return result;
    };
  };
})();

使用示例

1. 攔截全局函數

function test(name, age) { console.log('test:', name, age); }

aop({
  target: 'test',
  before: function() { console.log('→ before'); },
  after: function() { console.log('← after'); },
  around: function() { console.log('⟳ around'); }
});

test('Adam', 6);
// 輸出:⟳ around → before test: Adam 6 ← after ⟳ around

2. 攔截對象方法(保持 this 上下文)

var myObj = {
  name: 'Target',
  say: function() { console.log('say:', this.name); }
};

aop({
  context: myObj,
  target: 'say',
  before: function() { console.log('before say:', this.name); },
  after: function() { console.log('after say:', this.name); }
});

myObj.say(); // this 正確指向 myObj

3. 嵌套對象方法

aop({
  context: myObj.childObj,
  target: 'say',
  before: function() { console.log('child before:', this.age); }
});

實現細節與限制

  • 函數克隆:通過 toString() + eval 重建函數,**無法複製閉包變量**、**無法處理原生函數**、**嚴格模式下 eval 受限**。
  • 參數透傳:arguments 傳給所有通知與原函數。
  • 返回值:around 可選擇調用 original 並修改返回值(需手動調用)。
  • 異步支援:原實現同步;Promise/async 需包裝 await original.apply(...)。

生產級替代方案

  • Aspect.js:基於 Proxy/Reflect 的現代 AOP 库。
  • Melange:TypeScript 裝飾器風格 AOP。
  • 手動包裝:const orig = obj.method; obj.method = function(...args){ before(); try{return orig.apply(this,args)}finally{after()} }——最簡潔可控。
copyright © 萬盛學電腦網 all rights reserved