function debounce(fn, wait, immediate) {
var timer = null
return function () {
var args = arguments
var context = this
if (immediate && !timer) {
fn.apply(context, args)
}
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
一直没搞清楚,这个arguments是debounce这个函数的吗?请大佬详细讲讲。
用apply绑定,是与闭包有关吗?
假设你现在监听了一个鼠标移动事件:
当触发事件时,打印得到事件对象以及当前元素(el)。
现在给事件处理函数加上了防抖:
el.onmousemove = debounce(handler)
。对于
debounce(handler)
,返回值是一个函数,所以等同于el.onmousemove = denouceHandler
,只是一个新的事件处理函数而已,它的参数中就会包含事件对象,也就是 arguments 中包含事件对象。至于
fn.apply(context, args)
,前面提到handler
中打印 this 可以拿到正确的值(当前元素),这里即改变 this 的指向。于是乎在加了防抖函数之后去触发事件时,才能保证fn
内部能够拿到事件对象
以及 正确的this
值