原理

AOP 成为面向切片编程,在程序中主要用来解决一些系统层面上的问题,比如日志,事务,权限等。再不改变原有逻辑的基础上增加一些额外的功能。代理也是这个功能,读写分离也能用 aop 来做。
在前端中又如装饰器,前端埋点(在ajax的请求中包含一层自己的逻辑)。

实现before

  1. function fn(val) {
  2. console.log('一定的功能' + val)
  3. }
  4. Function.prototype.before = function (beforeFn) {
  5. let self = this;
  6. return function(){
  7. beforeFn();
  8. self.apply(self, arguments);
  9. };
  10. }
  11. const newFn = fn.before(function(){
  12. console.log('在函数执行前执行');
  13. })
  14. newFn('狮子');
  15. //输出
  16. //在函数执行前执行
  17. //一定的功能狮子

实现After

  1. Function.prototype.after = function (afterFn) {
  2. let self = this;
  3. return function () {
  4. self.apply(self, arguments);
  5. afterFn();
  6. }
  7. }
  8. const newFn2 = fn.after(function(){
  9. console.log('在函数之后执行');
  10. })
  11. newFn2('bear');
  12. //输出
  13. //一定的功能bear
  14. //在函数之后执行