高阶函数

83 阅读1分钟

高阶函数

基本概念

  1. 一个函数的参数是一个函数,可以称为高阶函数。(回调函数)
  2. 一个函数返回一个函数,也可以称之为高阶函数。(不单指闭包)

举个栗子

// 我们希望在调用coreFn之前需要先执行before再执行coreFn,并返回一个新函数提供执行
function coreFn() {
  console.log('core fn');
}
const newFn = coreFn.before(() => {
  console.log('before fn');
});

newFn();
  • 扩展公共方法,通过原型链扩展公共方法。
Function.prototype.before = function (beforeFn) {
  // 需要返回一个函数
  return () => { // 箭头函数,没有this 没有argument 没有原型链
    beforeFn();
    this(); // this指向coreFn
  }
}

// 打印结果
// before fn
// core fn
  • 我们也可以进行传参,拓展使用。
Function.prototype.before = function (beforeFn) {
  // 需要返回一个函数
  return (...args) => { // 箭头函数,没有this 没有argument 没有原型链
    beforeFn();
    this(...args); // this指向coreFn
  }
}
function coreFn(a, b, c) {
  console.log('core fn', a, b, c);
}
const newFn = coreFn.before(() => {
  console.log('before fn');
});

newFn(123);

// 打印结果
// beore fn
// core fn 1 2 3
  • 这里的before就是高阶函数,他接受一个函数作为参数,并且返回一个函数,在不修改原函数的情况下去做一些拓展功能,在平时的开发中会经常用到此类方案。