Skip to main content
Version: 3.28.0

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 to func. If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.
  • argsArray optional
    • : An array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function.

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 that call() accepts an argument list, while apply() 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 means new.target is undefined, and classes throw an error because they can't be called without new. Use Reflect.construct() or extends instead.