Reputation: 1140
I'm studying the post for a solution to debouncing:
I'm struggling to think of a situation where
func.apply(context, arguments);
is necessary, instead of just using
func();
I think 99% chances that it will only be used as a function. Under what circumstances will this be attached to an object? Can someone please show an example here? Thanks.
Upvotes: 2
Views: 125
Reputation: 11177
There are two things going on here in regards to the use of apply
:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
};
First, the context
is being captured outside of the setTimeout
callback. So whatever this
binding rule is used to determine the initial context (which is dependent on how the depounced function is called later), it is being passed through to the callback function.
Alternately, you could do something like:
setTimeout(function() {
...
func.apply(this, args);
}.bind(this), wait);
The second thing happening is the preservation of the arguments. apply
here is used as a way to transfer the arguments (again, importantly captured outside the setTimeout
callback) that you would pass to the original function. Because it takes an array
(as opposed to call), it makes for an easy transfer.
So if you had something like like:
debouncedFunction(a, b)
The inner func
is called appropriately as func(a, b)
.
Upvotes: 1
Reputation: 780852
debounce
is intended to work with functions that are called in any manner. If the function being debounced is called with a context or with arguments, those need to be passed through when it's called with debounce
.
So if you would normally make a call like:
foo.method(arg1, arg2);
then you should also be able to write:
debounced_method = debounce(foo.method);
foo.debounced_method(arg1, arg2);
Then when it calls the method, it receives this = foo
and arguments = arg1, arg2
.
Upvotes: 1