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

