Function.prototype.apply()
The apply()
method calls the specified function with a given this
value, and arguments
provided as an array (or an array-like object).
Syntax
apply(thisArg)
apply(thisArg, argsArray)
Parameters
thisArg
- : The value of
this
provided for the call tofunc
. If the function is not in strict mode,null
andundefined
will be replaced with the global object, and primitive values will be converted to objects.
- : The value of
argsArray
optional
Return value
The result of calling the function with the specified this
value and arguments.
Description
Note: This function is almost identical to
Function.prototype.call()
, except thatcall()
accepts an argument list, whileapply()
accepts a single array of arguments — for example,func.apply(this, ['eat', 'bananas'])
vs.func.call(this, 'eat', 'bananas')
.
Normally, when calling a function, the value of this
inside the function is the object that the function was accessed on. With apply()
, you can assign an arbitrary value as this
when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.
Warning: Do not use
apply()
to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which meansnew.target
isundefined
, and classes throw an error because they can't be called withoutnew
. UseReflect.construct()
orextends
instead.