高阶函数复习

99 阅读1分钟

高阶函数是一种函数使用技巧,一个函数满足

  1. 函数可以作为参数传递
  2. 函数可以作为返回值输出
  • 满足以上这两个条件之一,这个函数就是一个高阶函数. 可以看下Array.sort这个方法,它就可以将函数作为参数进行传递。
// 从大到小排列一个数字数组
let arr = [0,21,81,17]
arr.sort((x,y) => {
    return y - x;
})
console.log(arr); // [81, 21, 17, 0]

将函数作为返回值输出在开发中也是及其常见的

// 简单的单例模式实现
let getSingle = fn => {
    let ret;
    return function() {
        return ret || (ret = fn.apply(this, arguments));
    }
}
let getScript = getSingle(() => {
    return document.createElement('script');
})

let s1 = getScript();
let s2 = getScript();
console.log(s1 === s2);  // true

常见的高阶函数应用技巧有很多,比如函数柯里化

let currying = fn => {
    let args = []
    return function() {
        if (arguments.length === 0) {
            return fn.apply(this, args)
        } else {
            [].push.apply(args, arguments)
        }
    }
}

let a = function() {
    return Array.of(arguments)
}

let c = currying(a)

c(2) // undefined
c(3) // undefined
c() // [2, 3]

还有像常用的节流函数的使用

let throttle = (fn, interval) => {
    let timer
    return function() {
        let context = this
        let args = arguments
        if(!timer) {
            timer = setTimeout(() => {
                timer = null
                fn.apply(context, args)
            }, interval)
        }
    }
}