JavaScriptEasy
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
- Check that
thisis a function. - Normalise the context (
null/undefined→globalThis, primitives boxed withObject()). - Validate the arguments:
nullorundefinedmeans "no arguments"; otherwise it must be an array-like object, or throw aTypeErrorlike the native version does (fn.apply(ctx, 5)throws). - Convert array-likes (e.g.
arguments,{ length: 2, 0: "a", 1: "b" }) withArray.from. - Attach under a unique
Symbol, call with spread, delete infinally, 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-likes10 }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});2425console.log(Math.max.myApply(null, [3, 9, 4])); // 92627const 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 left3334// Array-likes and missing args35console.log(Array.prototype.join.myApply({ length: 3, 0: "a", 1: "b", 2: "c" }, ["-"])); // a-b-c36function count() {37 return arguments.length;38}39console.log(count.myApply(null), count.myApply(null, undefined), count.myApply(null, [1, 2])); // 0 0 24041// Invalid argument list throws like the native version42for (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}4950delete 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.