Difference between .call and .apply

In JavaScript, everything are objects , even Functions, and every objects has their properties and methods. Both .apply and .call are methods of Function object. Still, many people get confused with these two functions in JavaScript. Basically, they differ on how they handle function arguments . Both functions allow you to control the meaning of 'this' inside the called function, but the difference is in how arguments are passed to the function. The apply() method is identical to call() , except apply() requires an array as the second parameter. The array represents the arguments for the target method.


It calls a function with given values and arguments provided individually

foo.call(obj, arg1, arg2, arg3)


It calls a function with given values and arguments provided as an array or array object. example
foo.apply(obj, [arg1, arg2, arg3])
The first argument, in both cases, is the object reference that will represent 'this' inside the called function. So that's the difference between call and apply. Both can be called on functions, which they run in the context of the first argument. In call the subsequent arguments are passed in to the function as they are, while apply expects the second argument to be an array that it unpacks as arguments for the called function. Let's see an example which will make it clearer. example
var StudentName = { createName: function(firstName, middleName, lastName){ return firstName + ' ' + middleName + ' '+ lastName; } }; function displayName(firstName,middleName,lastName){ document.write(this.createName(firstName,middleName,lastName)); } //comma separated list or arguments displayName.call(StudentName,'John','Villa','Doe'); //arguments are passed as an array var nameArr = ['John', 'Villa','Doe']; displayName.apply(StudentName,nameArr);
John Villa Doe John Villa Doe