liveBook · Manning

Call

As explained in Secrets of the JavaScript Ninja, Third Edition

A JavaScript method that invokes a function with an explicitly supplied this value and individual arguments.

Function.call invokes a function with the first argument as its function context. Pass the function’s arguments individually after it; unlike apply, call does not take them as an array. 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 same sum function writes totals to different objects when invoked with call and apply; call receives its numbers individually. section 6.2.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the context-first syntax and individual argument list, contrasting call with apply without detailing implementation internals.
Examples
Demonstrates a sum function writing results to two objects and contrasts individual call arguments with apply’s array.
What you can do after
Apply call to invoke a function with a chosen context and individually supplied arguments.
How it connects
Connects call to this, function invocation, apply, bind, and method borrowing.

Also explained in

Compare how 2 books explain call →

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.