为什么我可以从滚动事件句柄的参数中获取事件对象,该事件对象传递给javascript中的闭包

时间:2019-03-29 07:43:16

标签: javascript closures

我对闭包中的参数感到困惑。参数是函数内部可访问的类数组对象,其中包含传递给该函数的参数的值。根据此规则,闭包本身根本没有参数。因此 fn.apply(this,a); 之前的参数应该为空,但实际上这些参数等于事件句柄函数 fn()的参数。为什么会发生?

    $(window).on('scroll', throttle(function (e) {
      console.log(arguments);

      let pageHeight = $('body').height(),
        scrollTop = $(window).scrollTop(),
        winHeight = $(window).height(),
        thresold = pageHeight - scrollTop - winHeight;
      if (thresold > -100 && thresold <= 20) {
        console.log('end');
      }
    }));


    function throttle(fn, delay = 300) {
      let execute = true;

      return function () {
        if (!execute) {
          return;
        }
        execute = false;
        setTimeout(() => {
          let a = arguments;
          console.log(arguments);// why the arguments is the arguments from fn which is event handle I pass into the closure
          fn.apply(this, a);
          execute = true;
        }, delay);
      }
    }

0 个答案:

没有答案