防抖和节流里边的 arguments是谁的啊

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绑定,是与闭包有关吗?

阅读 4.1k
4 个回答

假设你现在监听了一个鼠标移动事件:

function handler(e) { console.log(e, this); }

el.onmousemove = handler;

当触发事件时,打印得到事件对象以及当前元素(el)。

现在给事件处理函数加上了防抖:el.onmousemove = debounce(handler)
对于 debounce(handler),返回值是一个函数,所以等同于 el.onmousemove = denouceHandler,只是一个新的事件处理函数而已,它的参数中就会包含事件对象,也就是 arguments 中包含事件对象。

至于 fn.apply(context, args),前面提到 handler 中打印 this 可以拿到正确的值(当前元素),这里即改变 this 的指向。于是乎在加了防抖函数之后去触发事件时,才能保证 fn 内部能够拿到 事件对象 以及 正确的 this

这是一个函数体内的特殊变量,arguments就是传递给这个函数的参数列表,是一个类数组对象,你可以用一般数组方法去操作它,但是它不是一个数组。

比如函数

function A () {
  console.log(arguments)
}

调用A(1,2,3),输出[Arguments] { '0': 1, '1': 2, '2': 3 }
arguments[0] 就是1 类推。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题