JavaScript Methods: apply()

By: Dusty Arlia
Published on Saturday, January 25, 2014, 04:42 PM
Last Updated on Saturday, July 11, 2015 at 6:40 PM
Total Updates: 2

The call() and apply() methods allow you to indirectly invoke a function as if it were a method of some other object. Here are two examples:;

The ex_function() function is invoked as a method of the ex_object object. The first argument to both the call() and the apply() methods is the object on which the function is to be invoked. This argument is the invocation context and becomes the value of the this keyword within the body of the function.

These examples above behave just like this code below:

ex_object.ex_method = ex_function;   //Make ex_function a temporary method of ex_object
ex_object.ex_method();   //Use it
delete ex_object.ex_method   /Delete the temporary method

Any arguments after the invocation context are values that get passed to the function. The call() method can take extra arguments. The apply() method's second argument is an optional array of additional arguments. The apply() method's array argument is great for an arbitrary number of arguments. This array can be either a true array or an array-like object.