Name
Function.apply( ): invoke a function as a method of an object — ECMAScript v3
Synopsis
function.apply(thisobj,
args)
Arguments
-
thisobj The object to which
functionis to be applied. In the body of the function,thisobjbecomes the value of thethiskeyword. If this argument isnull, the global object is used.-
args An array of values to be passed as arguments to
function.
Returns
Whatever value is returned by the invocation of
function.
Throws
-
TypeError If this method is invoked on an object that is not a function or if this method is invoked with an
argsargument that is not an array or an Arguments object.
Description
apply( ) invokes the
specified function as if it were a method
of thisobj, passing it the arguments
contained in the args array. It returns
the value returned by the function invocation. Within the body of
the function, the this keyword
refers to the thisobj object.
The args argument must be an array
or an Arguments object. Use Function.call(
) instead if you want to specify the arguments to pass to
the function individually instead of as array elements.
Example
// Apply the default Object.toString( ) method to an object that // overrides it with its own version of the method. Note no arguments. Object.prototype.toString.apply(o); // Invoke the Math.max( ) method with apply to find the largest // element in an array. Note that first argument doesn't matter // in this case. var data = [1,2,3,4,5,6,7,8]; Math.max.apply(null, data);
See Also
Function.call( )
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access