Feb 24, 2008

apply() and call()

v3 defines two methods that are defined for all functions, call( ) and apply( ). These methods allow you to invoke a function as if it were a method of some other object. The first argument to both call( ) and apply( ) is the object on which the function is to be invoked; this argument becomes the value of the this keyword within the body of the function. Any remaining arguments to call( ) are the values that are passed to the function that is invoked. For example, to pass two numbers to the function f( ) and invoke it as if it were a method of the object o, you could use code like this:

f.call(o, 1, 2);
o.m = f;
o.m(1,2);
delete o.m;

The apply( ) method is like the call( ) method, except that the arguments to be passed to the function are specified as an array:

f.apply(o, [1,2]);
var biggest = Math.max.apply(null, array_of_numbers);
//Math.max(array_of_number) is not supported!