One place where using .apply is extremely useful is when wrapping or
"decorating" functions. A simple example might be writing a function that
can "throttle" other functions so they don't get called more often than,
say, once a second:
var someFunction = function () {
// let's say we do some sort of intense computation here
// and we don't want it to happen too often, lest it slow
// down the rest of the app unnecessarily
};
var throttle = function (throttledFunction) {
// this just returns a new function to use in place of throttledFunction
return function () {
var now = new Date();
if (!throttledFunction.lastCalled || now - throttledFunction.lastCalled
> 1000) {
throttledFunction.lastCalled = now;
// and here we use apply to pass whatever arguments this function got
to throttledFunction
return throttledFunction.apply(this, arguments);
}
};
};
someFunction = throttle(someFunction); // now you can only
call someFunction() once a second
It's a little complex, but hopefully it gives a pretty clear use case. The
"throttle" function returns a version of the function you passed it that can
only be called once a second. The crux of the whole thing, however is the
.apply function, which allows the throttled function to pass along whatever
arguments it received to the original function.
(Also note that the second argument passed to apply doesn't have to be an
array; it just has to be array-*like*, which basically means it has a
property named "length" that is a number and has values that can be accessed
by numbers between 0 and the value of "length.")
-Rob
On Sat, Jul 16, 2011 at 5:26 PM, Matthew Bramer <[email protected]> wrote:
> So, I'm taking away from your answer that I should in general use .call
>
> I have to tell you, I have a hard time following what you have said though.
> I'm pretty new to this stuff, so some of your answer is clearly above my
> knowledge level. Sometimes, I wish I had an easy button for JS. :/
>
> Cheers,
> Matt
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]
>
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]