JavaScript 中高阶函数

50 阅读1分钟

概念

一个函数接收一个或者多个函数作为参数,或者一个函数的返回结果是另外一个函数,这种函数被称为高阶函数

作用

  1. 拓展函数功能

    当想要在一个函数中新增一些功能,并且不修改原函数的代码的时候,可以使用高阶函数

const coreFun = (a, b) => {
  console.log(a, b)
}

coreFun.newFun = (callback) => {
  return (...args) => {
    callback()
    this(...args)
  }
}

const useNewFun = coreFun.newFun(() => {
  console.log('use fun')
})

useNewFun(1, 2)
  1. 实现函数分批传参
function sum(a, b, c) {
  return a + b + c
}

function apply(fn, ...firstArgs) {
  return (...secondArgs) => {
    return fn(...firstArgs, ...secondArgs)
  }
}

const add = apply(sum, 1, 2)
console.log(add(3))