假如咱们目前有一个小需要:
实现目标函数调用前后的业务逻辑办法。

// intro 实现test函数调用前后的业务逻辑办法;function test() {  console.log(2);};// 调用函数test();// expect 冀望输入如下// console.log(1);// console.log(2);// console.log(3);

思考一下咱们将会如何实现?

难点:
1、办法在绑在哪?
2、函数的执行程序。
3、this指向如何保障?
4、参数如何保障?

思路:
事实上咱们晓得在js代码中任何函数都是Function构造函数的实例对象,
既然要实现额定的性能就肯定会重写函数自身,意味着全新的函数,
故能够将办法绑定在所有函数的原型上;

实现如下:

// intro 实现test函数调用前后的业务逻辑办法;function test() {  console.log(2);};// 绑定办法Function.prototype.before = function(beforeFn) {  const _this = this;   // test调用 指向 原函数  return function() {   // return 两头函数    beforeFn();    // 前置函数    _this();       // 原函数 test  };    };Function.prototype.after = function(afterFn) {  const _this = this;   // 两头函数  return function() {   // 最终重写后的 test函数    _this();    // 两头函数    afterFn();  // 后置函数  };    };// 重写test = test.before(function() {      console.log(1);    })    .after(function() {      console.log(3);    })// 调用函数test();// 输入如下// console.log(1);// console.log(2);// console.log(3);

如此就能实现函数调用前后的业务逻辑办法啦。
更多的问题? this的指向如何保障呢?