Javascript’s call and apply are two mysterious functions that can be difficult to understand, but it’s worth taking the time to learn about them becuase they’re ver useful. They’re also very similar, but with one subtle but important difference.
call
call, or more properly, Function.call, is a property of all Javascript functions.
It allows you to run a function and define what the value of this will be inside the function, and also supply arguments to the function you are running. For example:
Any other arguments you pass to call are passed to the function you are calling as its arguments. Like so:
Neato, eh?
apply
apply is very similar, and can be run on any functions. It runs your function, and the first argument you pass is the same as in call: it will become the value of this.
The difference is that you don’t pass the other arguments individually, you pass them as an array.
Here’s the example above using apply:
See the difference? It’s subtle, but important.
In use
Here’s some great uses for call and apply…
arguments
Did you know that the arguments variable inside all functions is not actually an array? That means you can’t use all the nice array methods like pop, push and slice on it! If you want to turn arguments into an array, use call:
Here we’re using the slice method of an empty array.
slice copies elements out of one array and returns them as a new array. It starts at the index you supply in the first argument and finishes one before the index you supply in the second argument, or it goes all the way to the end if you don’t supply a second argument.
slice copies elements out of whatever object this refers to. Usually, inside slice, the value of this is the array we are calling slice on. In the above example, that would be the empty array. However, becase we are using call, this is in fact the array-like object arguments. slice copies each element out of arguments into a real array and returns it.
Nice.
Log it all
Let’s say you’re passing a callback to someone else’s library and you’re expecting data back, but you don’t know how many arguments you’re going to get. There’s a simple trick to allow you to console.log everything that’s passed to your callback.
Becuase apply takes an array of arguments to be passed to the function, you can sling it the array of arguments you recieved and have them logged out, all nicely formatted.
Note: you could actually just pass arguments as the second argument to apply, becuase it’s ‘array-like’ enough, but for now we’ll play it safe.
pub/sub
Here’s a bigger example.
I’ve put together a publisher/subscriber object called pubsub. It uses call and apply to implement some neat features. Take some time to run it, look through it and have a play.