Aspect Oriented Programming
核心代码与非核心代码的分离。
不修改原来的功能,而是在原有的基础上,(在前或在后)添加上新的功能
例子
Node 中读取文件、获取数据,处理数据,重新写入数据
- 读取文件获取数据
- 处理加工数据
- 重新写加文件
好处
编写 before、after 方法
- 在谁上面 / 下面
- 函数的执行顺序
- this 指向怎么保证
- 参数怎么保证 ```javascript Function.prototype.before = function (beforefn) { var _this = this; // 保存原函数的引用 return function () { // 返回包含了原函数和新函数的”代理”函数 beforefn.apply(this, arguments); // 先执行新函数,修正this return _this.apply(this, arguments); // 再执行原函数 }; };
Function.prototype.after = function (afterfn) { var _this = this; return function () { var ret = _this.apply(this, arguments); //先执行原函数 afterfn.apply(this, arguments); //再执行新函数 return ret; }; };
```javascriptfunction test() {console.log("test");}test = test.after(function () {console.log("a1");}).before(function () {console.log("b1");}).after(function () {console.log("a2");}).after(function () {console.log("a3");}).before(function () {console.log("b2");});test();/*b2b1testa1a2a3*/
