【JS很简单】——闭包

58 阅读1分钟

JavaScript 中函数是一等公民,体现为可以作为参数、返回值。使得 JS 轻松实现回调,闭包特性。

  • 私有化数据
  • 保存数据

模块化

  • 闭包
  • 单例
const moduleA = !function(){
    let time = Date.now()
    function queryData(){
        return {
            time,
            queryData
        }
    }
}()

惰性函数

function getCss(el, attr){
    if(window.getComputedStyle){
        getCss = function getCss(el, attr){
            return window.getComputedStyle(el)[attr]
        }
    }else{
        getCss = function getCss(el, attr){
            return el.currentStyle(attr)
        }
    }
    return getCss(el, attr)
}

函数柯里化

function curry(x){
    return function(...args){
        return args.reduce((pre, next)=> pre + next, x)
    }
}

Compose函数

function compose(...fn){
    return function(x){
        if(fn.length == 0) return x 
        return fn.reduce((pre, next)=> {
            if(typeof pre !== 'function') return pre
            return pre(next)
        } ,x)
    }
}

防抖

function debounce(fn, delay, immediate){
    let timer
    return function(...args){
        let context = this
        if(immediate){
            fn.apply(context,args)
            immediate = false
        }
        timer && clearTimeout(timer)
        timer = setTimeout(()=> void fn.apply(context, args), delay)
    }
}

节流

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