高阶函数的应用

316 阅读1分钟

1、什么是高阶函数

两个特点满足一个就是高阶函数

1)函数有一个参数是函数;常用回调函数

const cb = () => console.log('cb')

function fn(callback) {
    callback && callback()}

fn(cb)

2)函数返回一个函数;常用于闭包

function fn() {
    return function () {}
}

fn()

2、高阶函数能够解决什么问题

1)比如我们常用的装饰器模式(切片编程)。应用:给应用加日志,对原有的核心代码进行装饰,调用核心代码之前做一些事情,之后做一些事情。

function core() {
    // todo... 这里面是我们的业务代码
    console.log('core执行')
}

// 给函数类原型加上before方法
Function.prototype.before = function (beforeFn) {

    return (...args) => {
        beforeFn()
        this(...args)
    }
}

// 调用核心代码之前
const newFn = core.before(() => {
    console.log('core调用之前')
})

newFn() 
// core调用之前
// core执行

2)函数柯里化;数字累加举例,数据类型的判断

/**
* 判断变量数据类型
* typeof (不能区分对象)
* constructor (判断构造函数)
* instanceof
* Object.prototype.toString.call
*/

// 求和函数
function sum(a, b, c, d) {  return a + b + c + d}

/** 
* 柯里化函数
* @param Array arr 收集每次调用时传入的参数 
* */ const curring = (fn, arr = []) => {  
        // 拿参数个数
        const len = fn.length
        return function (...args) {    
            const newArr = [...arr, ...args]
            if (newArr.length === len) {              return fn(...newArr)                } else {
              return curring(fn, newArr)                }  
        }
    }
const newSum = curring(sum)
console.log(newSum(1)(2)(3)(4)); // 10
console.log(newSum(1, 2)(3)(4)); // 10

// 数据类型的判断
function isType(type, val) {  return Object.prototype.toString.call(val).toLowerCase() === `[object ${type}]`.toLowerCase()}const newIsType = curring(isType)const isString = newIsType('String')console.log(isString('22')); // true

3、总结

高阶函数在实际开发中运用的很多,除了上面两种用的少,还有场景的回调函数、闭包、promise、防抖、节流、数组的一些迭代方法(forEach、map)等。这里是做一个概念的区分。