MJingv / jehol-person-blog

Jehol's Blog 🙋 (hexo+react)
https://mjingv.github.io/JeholBlog/
0 stars 1 forks source link

闭包新理解 #103

Open MJingv opened 7 months ago

MJingv commented 7 months ago

闭包是什么?

哪些场景闭包无可替代?

MJingv commented 7 months ago

私有变量和let/const区别

const createCounter = () => {
    // 1.私有变量
    let counter = 0
    return () => counter++
}
const counter = createCounter()
console.log(counter())
console.log(counter())
console.log(counter())
MJingv commented 7 months ago

节流防抖中的闭包

节流

const throttle = (fn, delay) => {
    // 间隔1000ms执行
    let last = 0
    return (...args) => {
        let now = new Date()
        if (now - last > delay) {
            fn.apply(this, args)
            last = now
        }
    }
}

防抖

const debounce = (fn, delay) => {
    // 防抖 强制停止1s后再执行。eg.输入300ms后才能再输入
    let timer = null
    return (...args) => {
        clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}
MJingv commented 7 months ago

异步编程中的闭包