Thursday, August 4, 2011

Javascript : Call Vs Apply (Part 2)

This is part 2 of JavaScript Call Vs Apply.

Part 1 explained bit about of switching context in JavaScript and its uses. This part explains how to use Call and Apply for this and what is the difference between Call and Apply.

The only difference between Call and Apply is in how they handle the arguments. In Call you need to pass the arguments (as you do for normal function calls). In Apply you need to pass the arguments as an array. To see this in action, I am going to modify the function used in Part 1 by adding additional arguments:

function displayDetails(argOne, argTwo)
          alert(argOne + ‘:’ + argTwo);

Following is the syntax to invoke the above function using Call and Apply:, ‘one’, ’two’);
displayDetails.apply(object, [‘one’,’two’]);

As you could see from above, the only difference is the arguments in Call are sent separately but in Apply it is sent as an array.

One scenario where Apply could be preferred over Call is when you need to pass all the arguments of the parent function to the target function. For example, consider the following code:

function test(testOne, testTwo)
, testOne, testTwo); //works as expected.
displayDetails.apply(this, arguments); //works as expected.

Both the lines in the above function work correctly. It you are going to add another parameter to “test” function, then you would need to modify the first line (Call) but not the second (Apply).

function test(testOne, testTwo, testThree)
, testOne, testTwo, testThree); //need to add the additional parameter.
displayDetails.apply(this, arguments); //no changes required.

Hope this post was useful.

Happy coding!!

No comments:

Post a Comment