本文分享一個以 JavaScript 實作 AOP(Aspect Oriented Programming,面攤導向程式設計)的範例,可在不修改原函式的情況下,為它掛上前置、後置與環繞行為。
/*
// aop({options});
// By: adamchow2326@yahoo.com.au
// Version: 1.0
// Simple aspect oriented programming module
// support Aspect before, after and around
// usage:
// aop({
// context: myObject, // scope context of the target function.
// target: "test", // target function name
// before: function() { // before function will be run before the target function
// console.log("aop before");
// },
// after: function() { // after function will be run after the target function
// console.log("aop after");
// },
// around: function() { // around function will be run before and after the target function
// console.log("aop around");
// }
// });
var aop = (function() {
var options = {},
context = window,
oFn, oFnArg, targetFn, targetFnSelector,
beforeFn, afterFn, aroundFn,
cloneFn = function(Fn) {
if (typeof Fn === "function") {
return eval('[' + Fn.toString() + ']')[0];
}
return null;
},
checkContext = function() {
if (options.context) {
context = options.context;
}
if (typeof context[(options.target).name] === "function") {
targetFnSelector = (options.target).name;
targetFn = context[targetFnSelector];
} else if (typeof context[options.target] === "function") {
targetFnSelector = options.target;
targetFn = context[targetFnSelector];
}
if (targetFn) {
oFn = cloneFn(targetFn);
oFnArg = new Array(targetFn.length);
return true;
} else {
return false;
}
},
run = function() {
context[targetFnSelector] = function(oFnArg) {
if (aroundFn) { aroundFn.apply(this, arguments); }
if (beforeFn) { beforeFn.apply(this, arguments); } // 'this' is context
oFn.apply(this, arguments);
if (afterFn) { afterFn.apply(this, arguments); } // 'this' is context
if (aroundFn) { aroundFn.apply(this, arguments); }
};
};
return function(opt) {
if (opt && typeof opt === "object" && !opt.length) {
options = opt;
if (options.target && checkContext()) {
if (options.before && typeof options.before === "function") {
beforeFn = options.before;
}
if (options.after && typeof options.after === "function") {
afterFn = options.after;
}
if (options.around && typeof options.after === "function") {
aroundFn = options.around;
}
run();
}
}
};
})();
// -------------------- 測試範例 --------------------
// 一、aop 修改全域函式
function test(name, age) {
console.log("test fn. name = " + name + " age: " + age);
}
aop({
target: "test",
before: function() {
console.log("aop before");
},
after: function() {
console.log("aop after");
},
around: function() {
console.log("aop around");
}
});
// 執行
test("adam", 6);
// 二、aop 修改物件中的方法
var myobj = {
myName: "testName",
sayName: function() {
console.log(this.myName);
},
childObj: {
age: 6,
say: function() {
console.log(this.age);
}
}
};
aop({
context: myobj,
target: "sayName",
before: function() {
console.log("aop before say name = " + this.myName);
},
after: function() {
console.log("aop after say name = " + this.myName);
},
around: function() {
console.log("aop around say name = " + this.myName);
}
});
// 執行
myobj.sayName();
aop({
context: myobj.childObj,
target: "say",
before: function() {
console.log("aop before say name = " + this.age);
},
after: function() {
console.log("aop after say name = " + this.age);
},
around: function() {
console.log("aop around say name = " + this.age);
}
});
myobj.childObj.say();
整個模組用 IIFE 封裝,對外只暴露一個函式,內部流程分三步:
· checkContext():先確認 context(預設是 window),再依 target 找到要被攔截的函式,並用 cloneFn 複製一份原始函式的參照保存起來。
· run():把 context 上原本的方法替換成一個新函式,新函式依序執行 around → before → 原函式 → after → around。
· 所有 apply(this, arguments) 都保留了原本的 this 與參數,因此攔截後行為與原函式一致。
· cloneFn 用 eval('[' + Fn.toString() + ']')[0] 的技巧把函式轉成另一個獨立實例,避免後續替換時影響參照。
· checkContext 裡有兩段幾乎相同的判斷,目的是同時支援「傳入函式物件」與「傳入函式名稱字串」兩種寫法。
· 三個測試範例分別示範了攔截全域函式、物件方法與巢狀物件方法,可以看到 this 正確指向所屬物件。
實務提醒:這份實作有個小 bug 值得注意——判斷 around 時誤寫成 typeof options.after === "function",應該檢查 options.around 才對。另外 cloneFn 依賴 eval 與 toString(),遇到閉包或原生函式時可能失效;在現代專案中,若要達到相同效果,更建議使用 ES6 的 Proxy、Reflect 或裝飾器(decorator)語法來實作 AOP,安全性和可維護性都更好。