liveBook · Manning

Apply

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 as an array-like object.

When a function runs as a browser event handler, its this value may be the event target rather than the object that owns the function. apply lets you invoke a function with an explicitly chosen this value and pass its arguments as an array of values. section 4.2.4

Call and apply both take the desired context as their first argument. apply takes one more argument containing the function’s arguments; call takes those arguments individually. Use apply when the array form fits the values you need to pass. 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

Compare apply and call invoking the same function with different contexts and arguments. section 4.2.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains apply’s context and argument parameters with a worked comparison to call.
Examples
Demonstrates apply with a juggle function and contrasts it with call using separate objects.
What it assumes
Assumes familiarity with JavaScript functions and this while contrasting function, method, and constructor invocation.
What you can do after
Apply it to invoke a function with a chosen context and arguments supplied as an array.
How it connects
Connects apply to call, function invocation, this, and callback context.

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.