AOP (Aspect Oriented Programming)面向切片编程:
关键词:AOP,面向切片编程,装饰器,装饰者模式
敲重点: AOP就是在不改变函数的情况下,给函数添加新的功能 ,实现原理是在执行原函数之前或者之后执行任意函数
//前置切片 在原函数之前执行
Function.prototype.before=function(fn){
const self =this;
return function(){
fn.call(this,arguments); //原函数
self.call(this,arguments);//要执行的函数
}
}
//后置切片 在原函数之后执行
Function.prototype.after=function(fn){
const self =this;
return function(){
self.call(this,arguments);//要执行的函数
fn.call(this,arguments); //原函数
}
}
function demo(){
console.log("demo");
}
demo.before(function(){
console.log("切片1");
})
.before(function(){
console.log("切片2");
})
.after(function(){
console.log("切片3");
})();
//输出顺序: 切片2 切片1 demo 切片3
是不有点像promise的链式写法了(hahhaha1),无论是before,after还是Promise的then函数,他们返回的都是一个函数
AOP一改之前的纵向写法,即在函数内追加新的代码,即便对函数进行了封装,调用函数的代码依然要写入函数内部。而AOP无需将代码写入函数内部,不会影响该函数本身的业务逻辑,因此也叫横向切片,一个函数对应一个切片,在执行原函数之前或者之后可以自由添加任意多个切片;