实现AOP
大约 1 分钟javascript
在原型链上为 Function 添加函数 before 和 after,依次表示在执行函数之前调用的函数和之后调用的函数 下面例子中函数 billNew 和 billOpen 都是原始函数,为 billNew 制作 AOP 效果,在执行函数之前打印内容,执行之后也打印内容。同时前后函数都可以接受原函数的参数,前函数如果返回 false 可阻止原函数的执行,同时也会阻止后函数的执行。注意一定要覆盖原函数。
let billNew = function(){
console.log('新增一个单据');
}
var billOpen = function(){
console.log('打开原始单据');
}
// 在方法之前被执行 = aop.before
Function.prototype.before = function(beforeFunc){
const __self = this;// 保存被拦截函数的this
return function(){// 代理函数
// before 函数返回 false 则不调用原函数
// after 函数也不会执行
if(beforeFunc.apply(this,arguments) === false){
return false;
}
return __self.apply(this,arguments);
}
}
// 在方法之后被执行 = aop.after
Function.prototype.after = function(afterFunc){
const __self = this;
return function(){
const ret = __self.apply(this,arguments);
if(ret === false){// 原函数返回 false 则不执行后置函数
return false;
}
afterFunc.apply(this,arguments);
return ret;
}
}
const billNewAop = function(func,funcName){
return func = (function(){
let d;
return func.before(function(arg1){
console.log('aop.before argument:' + arg1 + ',返回false,取消原函数的调用');
return true;
}).after(function(arg1){
console.log('aop.after argument:' + arg1);
})
})();
}
billNew = billNewAop(billNew,'billNew');
const billOpenApply = function(){
billOpen.apply(this,arguments);
}
