防抖装饰器
function debounce(fn, ms) {
let timer
return function (...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms)
}
}
节流装饰器
function throttle(fn, ms) {
let timer
return function(...args) {
if (timer) return
timer = setTimeout(()=>{timer = null}, ms)
fn.call(this, ...args)
}
}
关键知识点
一个好的装饰器,不但应该实现功能,还应考虑到通用性。主要有以下2点:
(1) 支持多参数
(2)支持普通函数/对象方法(涉及对this的处理)
