JavaScriptMedium
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
- Transparent wrappers and decorators: logging, timing, memoize, once, retry.
fn.apply(this, args)forwards both the caller'sthisand every argument, so wrapping a method does not break it. - Borrowing methods for objects that are not the method's usual type: array-likes,
arguments,NodeListin old browsers. - Monkey-patching safely: keep the original method and call it with the same context:
original.apply(this, arguments). Polyfills and instrumentation code use this. - Proxy
applytraps:apply(target, thisArg, args) { return Reflect.apply(target, thisArg, args); }. - 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
fnmight have an ownapplyproperty (rare, e.g. in proxies or mocks), callReflect.apply(fn, thisArg, args)orFunction.prototype.apply.call(fn, thisArg, args).
Code example
js
1// 1. Transparent decorator: keeps `this` and all arguments2function 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}1213class 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 place20console.log(new Cart().total(2)); // logs the time, then 14 - `this` still works2122// 2. Monkey-patching with the original preserved23const 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"]3132// 3. Borrowing a method for an array-like33function joinArgs() {34 return Array.prototype.join.apply(arguments, [" + "]);35}36console.log(joinArgs(1, 2, 3)); // "1 + 2 + 3"3738// 4. Proxy apply trap39const 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.