Calling a Function Using function.apply

Another way to invoke functions in JavaScript is using the .apply() method. The syntax for .apply() is as follows: functionName.apply(thisArg, [array]). "functionName" refers to the function being called. However, with .apply(), an array containing all values can be sent instead of individual arguments. Additionally, "thisArg" specifies the object that "this" references inside the invoked function.

Description

Note: This function is almost identical to call(), except that the function arguments are passed to call() individually as a list, while for apply() they are combined in one object, typically an array - for example, func.call(this, "eat", "bananas") vs. func.apply(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.

You can also use any kind of object which is array-like as the second parameter. In practice, this means that it needs to have a length property, and integer ("index") properties in the range (0..length - 1). For example, you could use a NodeList, or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }. You can also use arguments, for example:

function wrapper() {
  return anotherFn.apply(null, arguments);
}

With the rest parameters and parameter spread syntax, this can be rewritten as:

function wrapper(...args) {
  return anotherFn(...args);
}

In general, fn.apply(null, args) is equivalent to fn(...args) with the parameter spread syntax, except args is expected to be an array-like object in the former case with apply(), and an iterable object in the latter case with spread syntax.

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.