liveBook · Manning

Apply

As explained in Secrets of the JavaScript Ninja, Third Edition

A JavaScript method that invokes a function with an explicitly supplied this value and an array-like collection of arguments.

Function.prototype.apply invokes a function with an explicitly chosen this value and supplies its arguments as an array of values. This lets you use a function as though it were a method of another object, without attaching it there. section 6.2.4

Choose apply when you need to:

  • Set the function context: the first argument becomes this. section 6.2.4
  • Pass arguments from an array: unlike call, apply takes the argument values together as one array. For a modern alternative, spread an array into a function call. section 6.2.4
  • Borrow a method: invoke a function with another object as its context, even if the function is not attached to that object. section 6.2.4
Listing 6.4 Using the apply and call methods to supply the function context
function juggle(...numbers: number[]) { #A
  let result = 0; #A
  for (const number of numbers) { #A
    result += number; #A
  } #A
  this.result = result; #A
} #A
 
const ninja1 = { result: 0 };
const ninja2 = { result: 0 };
 
juggle.apply(ninja1, [1, 2, 3, 4]); #B
juggle.call(ninja2, 5, 6, 7, 8); #C
 
console.assert(ninja1.result === 10, "juggled via apply");
console.assert(ninja2.result === 26, "juggled via call");

The example runs the same summing function with two objects as its context: apply receives an array of numbers, while call receives the numbers separately. section 6.2.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains context and argument passing, compares call, and notes spread as a modern alternative.
Examples
Demonstrates method borrowing with a summing function and contrasts apply with call.
What it assumes
Assumes familiarity with function arguments and invocation, then explains how invocation affects this.
What you can do after
Apply apply to invoke a function with a chosen context and array-supplied arguments.
How it connects
Connects apply to this, function invocation, call, and the spread operator.

Also explained in

Compare how 2 books explain apply →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.