Here the “execute” function calls “func” and the function “func” defined in T is executed. Now let’s try to tweak the function “execute” in such a way so that it will accept a object and a function name as parameter and execute that function defined in that object.
- thisObj is the object that will be used as "this" i.e. object on which the function will be invoked
- argArray is the argument array used to pass argument values to the function which is invoked
“obj[func]” retrieves the function object based on the function name from the hash of “obj” and then “apply” is invoked on that function object.
As a next step let’s modify our function to accept few parameters.
The parameters are passed using the array “p”.
call([thisObj[, arg1[, arg2[, [, argN]]]]]) where
- thisObj (optional) - The object to be used as the current object on which the function is invoked
- arg1, arg2, , argN (optional list) - A list of arguments to be passed to the method.
The main difference with “apply” is in the way the parameters are handled, instead of a parameter array it accepts individual parameters.This makes it rigid compared to “apply”.
The following code shows the use of call.
If you are using Underscore.js this can be achieved more easily with _.bind function.
_.bind(function, object, *arguments) where
- function is the function object which needs to be invoked
- object is the current object on which the function is invoked
- *arguments are arguments values which the function expects
Our sample code is modified with _.bind
The _.bind function internally uses apply as shown below.