Using apply is related to the context of the function ( this ) and passing arguments.
First, I think you should know when the this keyword is implicitly set:
1- When a function is called as a method (a function is called as a member of an object):
obj.method();
2- Normal function call:
myFunction();
3- When the new operator is used:
var obj = new MyObj();
That's when apply and call come in, these methods allow you to set the context explicitly when calling the function, for example:
function test(a) { alert(this + a); } test.call('Hello', ' world!');
In the above code, when the test function is called, setting the this to String ( 'Hello' ) and passing the argument a ( ' world.' ).
Both, call and apply change the context of the executing function ( this ) inside the called function, but the difference between them is that with apply , you can send an Array or Array-like object as arguments to the function that will be executed, which is extremely useful for example:
function sum() { var result = 0; for (var i = 0; i < arguments.length; i++) { result += arguments[i]; } return result; } var args = [1,2,3]; sum.apply(null, args);
This can lead to very unpleasant, bad (and general) eval calls like:
eval('sum(' + args.join() +')');
In another example, the Math.max and Math.min methods, these methods can take an arbitrary number of arguments, such as:
var max = Math.max(2,4,6,8);
But what if you have an array of numbers?
var numbers = [2,4,6,8]; numbers.push(10); var max = Math.max.apply(null, numbers);
Also note that when null or undefined used as the this argument with call or apply , the this object will refer to the Global object (similar to case # 2, calling a normal function).
For the Math.max example, the context is not significant because they are similar to the "static" methods, the this keyword is not used internally ...