跳到主要内容

面向切面编程(AOP)

介绍

面向切面编程也叫函数劫持

面向切面编程思想 将与业务模块无关却为业务模块所共同调用的逻辑封装起来,便于减少系统重复代码,降低模块间的耦合度,有利于未来的可操作性和可维护性。

面向切面编程表现 就是两个函数,在Function的原型上加上beforeafter,在函数执行之前或者之后执行,相当于无侵入把一个函数插入到另一个函数的前面或者后面。

实现

通过箭头函数改变this指向的方式实现

function say(who){
console.log(who+'说话中');
}
Function.prototype.before=function(callback){
return (...argus)=>{
callback(argus);
return this(argus);
}
}
Function.prototype.after=function(callback){
return (...argus)=>{
const result=this(argus)
callback(argus);
return result;
}
}

const newSay=say.before(function(who){
console.log(who+'说话前');
}).after(function(who){
console.log(who+'说话后');
});
newSay('张文强');

通过apply改变this指向的方式实现

function say(who){
console.log(who+'说话中');
}
Function.prototype.before=function(callback){
/**
* @description: this 为调用 before 时的 say 函数
*/
const that=this;
return function(...argus){
callback.apply(this,argus);
return that.apply(this,argus);
}
}
Function.prototype.after=function(callback){
/**
* @description: this 为调用 before 时的 say 函数
*/
const that=this;
return function(...argus){
const result=that.apply(this,argus)
callback.apply(this,argus);
return result;
}
}

const newSay=say.before(function(who){
console.log(who+'说话前');
}).after(function(who){
console.log(who+'说话后');
});
newSay('张文强');

场景

  • 无侵入统计某个函数的执行时间
  • 表单校验
  • 统计埋点
  • 方式csrf攻击