Open MJingv opened 9 months ago
let
可以创建块级作用域变量const createCounter = () => {
// 1.私有变量
let counter = 0
return () => counter++
}
const counter = createCounter()
console.log(counter())
console.log(counter())
console.log(counter())
节流
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)
}
}
闭包是什么?
哪些场景闭包无可替代?