first of all, you have to understand that the function of throttle is to accept a function and return a new function, which has throttling function
.
usage would look like this:
function handleClick(param) {console.log('clicked', param)};
const throttledHandleClick = throttle(handleClick, 2000)
// clicked
throttledHandleClick('p')
throttledHandleClick('p')
throttledHandleClick('p')
so what you mean by arguments is actually
.
{
0 : 'p',
}
if you don't fn.apply (that,arguments), but fn (), then parameters will be lost
about this, this should depend on how the function is generated, throttle (handleClick, 2000)
, so this is window. Rather than depending on how the final function throttledHandleClick
is called, as you write.
if according to my understanding, it should be written like this:
function throttle(fn,interval){
var timer,
isFirst = true;
that = this; //
return function(){
if(isFirst){
fn.apply(that,arguments)
return isFirst = false
}
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
fn.apply(that,arguments)
}, interval || 1000);
}
}
arguments
is the parameter passed when the current function is called. This is a special built-in parameter, and the value of another method block is different, so use var args = arguments
to copy a copy of the parameter when the current function is called.
var that = this
is also a copy of the current context, or this
pointing.
these two lines of code are a copy of the call in the following timer, which involves a series of knowledge points such as this
pointing, scope, and so on.
this should be habitual writing.
in the case of this code, it does not involve the context change caused by the construction closure, and it will work without this step of referencing.