In Javascript, when you use a function as a first-class-object, you can call the function directly without any special context:
function execute(func) {
func();
}
where the context is the value of this
in the function when it’s executed.
If you’re not invoking the function with any arguments, it doesn’t really matter whether you use .apply
or .call
:
function execute(func, context) {
// these two statements have the same effect
func.call(context);
func.apply(context);
}
But as soon as you need to pass arguments…
function executeWith123(func, context) {
// these two statements also have the same effect
func.call(context, 1, 2, 3);
func.apply(context, [1, 2, 3]);
}
The difference is that with call
, you can write as many arguments as you need, which is handy when you know exactly which and how many arguments you’re passing. With apply
, it’s easier to use a variable number of arguments.
I used to have to always look up the difference between call
and apply
, until I realized:
Function.apply takes an array: A is for Apply and Array.
I hope that saves you the pain of looking up the documentation or guessing and picking the wrong one next time.
About the Author