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
