JS如何实现AOP
本文首发于个人博客 Cyy’s Blog
转载请注明出处 https://cyyjs.top/blog/5c45450cee82320b23674353
# 介绍
AOP(面相切面编程)主要作用是把一些跟核心业务逻辑模块无关的功能抽离出来。
例如:日志统计,异常处理等。把这些功能抽离出来后,通过"动态植入"的方法,掺入到业务逻辑模块中。
这样做的好处是保证业务逻辑模块的纯净和高内聚,其次可以方便的复用日志统计等功能模块。
# 如何实现
通常可以通过扩展Function.prototype来做到这一点:
// 前置函数
Function.prototype.before = function(beforefn) {
let __self = this; // 保存函数引用
return function() { // 返回包含了原函数和新函数的"代理"函数
beforefn.apply(this, arguments); // 执行新函数,修改this
return __self.apply(this, arguments); // 执行原函数
}
};
// 后置函数
Function.prototype.after = function(afterfn) {
let __self = this;
return function() {
let ret = __self.apply(this, arguments);
afterfn.apply(this, arguments);
return ret;
}
};
let func = function() {
console.log(2);
};
func = func.before(function() {
console.log(1);
}).after(function() {
console.log(3);
});
// 调用函数
func();
// 输出 1 2 3
