**切面 (Aspect)**:橫切關注點(日誌、計時、權限、事務)。
**切點 (Pointcut)**:目標函數調用位置。
**通知 (Advice)**:before (前)、after (後)、around (環繞)。
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;
};
};
})();
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
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
aop({
context: myObj.childObj,
target: 'say',
before: function() { console.log('child before:', this.age); }
});
toString() + eval 重建函數,**無法複製閉包變量**、**無法處理原生函數**、**嚴格模式下 eval 受限**。arguments 傳給所有通知與原函數。around 可選擇調用 original 並修改返回值(需手動調用)。await original.apply(...)。const orig = obj.method; obj.method = function(...args){ before(); try{return orig.apply(this,args)}finally{after()} }——最簡潔可控。