JavaScriptMedium
Implement Function.prototype.call
A call polyfill runs the function immediately with a given this: temporarily attach the function to the context object under a unique Symbol key, invoke it as a method (so this becomes the object), delete the key, and return the result.
Steps
- Ensure
this(the function being called) is callable; otherwise throwTypeError. - Normalise the context:
null/undefined→globalThis(sloppy-mode behaviour; strict-mode functions would actually receiveundefined, which this trick cannot reproduce fornull).- Primitives → box them with
Object(value)so a property can be attached.
- Use a
Symbolas the temporary key so it can never collide with an existing property and does not show up in normal key listings. - Call
context[key](...args), which setsthistocontext. - Always delete the key, even if the function throws (use
try/finally). - Return the result.
Limitations to mention
- Fails on frozen or non-extensible objects (you cannot add the temporary property). Real engines do not have this problem; a fallback is
Reflect.apply, but that defeats the purpose of the exercise. - Strict-mode semantics for
null/undefinedand primitives are approximated.
Why it is asked
It shows you understand that this is determined by how a function is called (method call syntax), and attention to cleanup and collisions.
Code example
js
1Object.defineProperty(Function.prototype, "myCall", {2 value: function myCall(context, ...args) {3 if (typeof this !== "function") throw new TypeError("myCall must be called on a function");4 const ctx = context == null ? globalThis : Object(context); // box primitives5 const key = Symbol("fn"); // unique, can't collide6 ctx[key] = this;7 try {8 return ctx[key](...args); // method call -> `this` is ctx9 } finally {10 delete ctx[key]; // always clean up11 }12 },13 writable: true,14 configurable: true,15 enumerable: false,16});1718function introduce(greeting, punctuation) {19 return `${greeting}, I'm ${this.name}${punctuation}`;20}2122const ada = { name: "Ada" };23console.log(introduce.myCall(ada, "Hi", "!")); // Hi, I'm Ada!24console.log(Object.getOwnPropertySymbols(ada).length); // 0 - temporary key removed2526// Primitives are boxed27function describe() {28 return `${typeof this}: ${this.toUpperCase()}`;29}30console.log(describe.myCall("hello")); // object: HELLO3132// Cleanup happens even if the function throws33function fails() {34 throw new Error("boom");35}36const target = {};37try {38 fails.myCall(target);39} catch (e) {40 console.log(e.message, Object.getOwnPropertySymbols(target).length); // boom 04142}4344// Same results as the native call45console.log(introduce.myCall(ada, "Hey", ".") === introduce.call(ada, "Hey", ".")); // true4647delete Function.prototype.myCall;
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.