Implement Function.prototype.apply

apply is call with the arguments supplied as an array: attach the function to the context under a temporary Symbol, invoke it with the spread argument list, clean up, and return the result, treating a missing or null argument list as no arguments.

Steps

  1. Check that this is a function.
  2. Normalise the context (null/undefined → globalThis, primitives boxed with Object()).
  3. Validate the arguments: null or undefined means "no arguments"; otherwise it must be an array-like object, or throw a TypeError like the native version does (fn.apply(ctx, 5) throws).
  4. Convert array-likes (e.g. arguments, { length: 2, 0: "a", 1: "b" }) with Array.from.
  5. Attach under a unique Symbol, call with spread, delete in finally, return.

Differences from call

Only the argument format. With modern spread syntax, fn.call(ctx, ...args) and fn.apply(ctx, args) are interchangeable; apply is convenient when you already hold an array or arguments object, for example when forwarding inside wrappers.

Limits to mention

  • Engines cap the number of arguments a call can take; spreading huge arrays can throw RangeError (same as native).
  • The temporary-property trick fails on frozen objects.

Code example

js
1Object.defineProperty(Function.prototype, "myApply", {
2 value: function myApply(context, argsList) {
3 if (typeof this !== "function") throw new TypeError("myApply must be called on a function");
4 let args = [];
5 if (argsList != null) {
6 if (typeof argsList !== "object" && typeof argsList !== "function") {
7 throw new TypeError("CreateListFromArrayLike called on non-object");
8 }
9 args = Array.from(argsList); // supports array-likes
10 }
11 const ctx = context == null ? globalThis : Object(context);
12 const key = Symbol("fn");
13 ctx[key] = this;
14 try {
15 return ctx[key](...args);
16 } finally {
17 delete ctx[key];
18 }
19 },
20 writable: true,
21 configurable: true,
22 enumerable: false,
23});
24
25console.log(Math.max.myApply(null, [3, 9, 4])); // 9
26
27const account = { owner: "Ada", balance: 100 };
28function withdraw(amount, fee) {
29 this.balance -= amount + fee;
30 return `${this.owner} has ${this.balance} left`;
31}
32console.log(withdraw.myApply(account, [30, 2])); // Ada has 68 left
33
34// Array-likes and missing args
35console.log(Array.prototype.join.myApply({ length: 3, 0: "a", 1: "b", 2: "c" }, ["-"])); // a-b-c
36function count() {
37 return arguments.length;
38}
39console.log(count.myApply(null), count.myApply(null, undefined), count.myApply(null, [1, 2])); // 0 0 2
40
41// Invalid argument list throws like the native version
42for (const fn of [() => count.apply(null, 5), () => count.myApply(null, 5)]) {
43 try {
44 fn();
45 } catch (e) {
46 console.log(e.name); // TypeError (x2)
47 }
48}
49
50delete Function.prototype.myApply;

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