liveBook · Manning

Call

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript Function method that invokes a function with an explicit this value and arguments supplied individually.

Calling a function as a method, constructor, or plain function affects its this value. call lets you choose that context explicitly: its first argument becomes this, and the remaining arguments are passed individually. section 4.2 section 4.2.4

Use call when you want to control the function context:

  • Pass the desired context first, followed by the function’s arguments: juggle.call(ninja2, 5, 6, 7, 8). section 4.2.4
  • Unlike call, apply takes the context first and then an array of argument values. section 4.2.4
  • call can also set the context for each callback invocation, as in a forEach example that makes each list item the callback’s this value. section 4.2.4
Listing 4.11. Using the apply and call methods to supply the function context
function juggle() {                                  #A
  var result = 0;                                    #A
  for (var n = 0; n < arguments.length; n++) {       #A
    result += arguments[n];                          #A
  }                                                  #A
  this.result = result;                              #A
}                                                    #A

var ninja1 = {};                                     #B
var ninja2 = {};                                     #B

juggle.apply(ninja1,[1,2,3,4]);                      #C
juggle.call(ninja2, 5,6,7,8);                        #D

assert(ninja1.result === 10, "juggled via apply");       #E
assert(ninja2.result === 26, "juggled via call");        #E

See call and apply used with the same function to supply different contexts and arguments. section 4.2.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Demonstrates explicit contexts through function calls and callbacks, contrasting positional arguments with apply’s array.
Examples
Uses a juggle function to set object results and a forEach callback to make each item its context.
What it assumes
Builds on distinguishing function, method, and constructor invocation and their effects on this.
What you can do after
Apply call to choose a callback’s this value and pass its arguments individually.
How it connects
Connects function invocation, this, apply, callbacks, and event handlers.

Related concepts

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