Skip to content
On this page

什么是高阶函数

  1. 一个函数返回的函数那么这个函数就是高阶函数
  2. 一个函数的参数是一个函数也是高阶函数

我们可以通过包装一个函数,对现有的逻辑进行拓

javascript
function core(a, b, c) {
  console.log("核心代码", a, b, c);
}
1
2
3

一个函数的参数是一个函数也是高阶函数

javascript
core.before = function (cb) {
  // 箭头函数的特点 1)没有 this 的执行 2)没有 arguments 3)没有 prototype
  // this = core
  return (...arg) => {
    cb();
    this(...arg);
  };
};

let newCore = core.before(function () {
  console.log("before");
});

newCore(1, 2, 3); // 对原来的函数进行拓展
1
2
3
4
5
6
7
8
9
10
11
12
13
14

将方法集成函数,则可以直接调用

javascript
Functoion.prototype.before = function (cb) {
  return (...arg) => {
    cb();
    this(...arg);
  };
};

function test(params) {
  console.log(params);
}

test.before(function () {
  console.log("before");
})(22)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
沪ICP备20006251号-1