What is function.prototype.apply used for?

Function.prototype.apply(thisArg, argsArray) invokes a function with an explicit this and an array of arguments; today it is mainly used for forwarding calls in wrappers and decorators, borrowing methods, and inside Proxy traps, since spread syntax replaced its older array-spreading role.

Practical uses today

  1. Transparent wrappers and decorators: logging, timing, memoize, once, retry. fn.apply(this, args) forwards both the caller's this and every argument, so wrapping a method does not break it.
  2. Borrowing methods for objects that are not the method's usual type: array-likes, arguments, NodeList in old browsers.
  3. Monkey-patching safely: keep the original method and call it with the same context: original.apply(this, arguments). Polyfills and instrumentation code use this.
  4. Proxy apply traps: apply(target, thisArg, args) { return Reflect.apply(target, thisArg, args); }.
  5. Calling with a computed argument list when you also need a specific this.

What it used to be used for

Math.max.apply(null, arr) and Array.prototype.push.apply(a, b) to spread arrays into arguments. Now write Math.max(...arr) and a.push(...b).

Gotchas

  • The argument array can hit engine limits on the number of arguments (around tens to hundreds of thousands).
  • Arrow functions ignore thisArg.
  • If fn might have an own apply property (rare, e.g. in proxies or mocks), call Reflect.apply(fn, thisArg, args) or Function.prototype.apply.call(fn, thisArg, args).

Code example

js
1// 1. Transparent decorator: keeps `this` and all arguments
2function timed(fn) {
3 return function (...args) {
4 const start = performance.now();
5 try {
6 return fn.apply(this, args);
7 } finally {
8 console.log(`${fn.name} took ${(performance.now() - start).toFixed(2)}ms`);
9 }
10 };
11}
12
13class Cart {
14 items = [3, 4];
15 total(multiplier = 1) {
16 return this.items.reduce((a, b) => a + b, 0) * multiplier;
17 }
18}
19Cart.prototype.total = timed(Cart.prototype.total); // wrap a method in place
20console.log(new Cart().total(2)); // logs the time, then 14 - `this` still works
21
22// 2. Monkey-patching with the original preserved
23const originalPush = Array.prototype.push;
24const tracked = [];
25tracked.push = function (...items) {
26 console.log("pushing", items);
27 return originalPush.apply(this, items);
28};
29tracked.push("a", "b");
30console.log([...tracked]); // ["a", "b"]
31
32// 3. Borrowing a method for an array-like
33function joinArgs() {
34 return Array.prototype.join.apply(arguments, [" + "]);
35}
36console.log(joinArgs(1, 2, 3)); // "1 + 2 + 3"
37
38// 4. Proxy apply trap
39const safeDivide = new Proxy((a, b) => a / b, {
40 apply(target, thisArg, args) {
41 if (args[1] === 0) return NaN;
42 return Reflect.apply(target, thisArg, args);
43 },
44});
45console.log(safeDivide(10, 2), safeDivide(1, 0)); // 5 NaN

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app