原理
AOP 成为面向切片编程,在程序中主要用来解决一些系统层面上的问题,比如日志,事务,权限等。再不改变原有逻辑的基础上增加一些额外的功能。代理也是这个功能,读写分离也能用 aop 来做。
在前端中又如装饰器,前端埋点(在ajax的请求中包含一层自己的逻辑)。
实现before
function fn(val) {console.log('一定的功能' + val)}Function.prototype.before = function (beforeFn) {let self = this;return function(){beforeFn();self.apply(self, arguments);};}const newFn = fn.before(function(){console.log('在函数执行前执行');})newFn('狮子');//输出//在函数执行前执行//一定的功能狮子
实现After
Function.prototype.after = function (afterFn) {let self = this;return function () {self.apply(self, arguments);afterFn();}}const newFn2 = fn.after(function(){console.log('在函数之后执行');})newFn2('bear');//输出//一定的功能bear//在函数之后执行
