Implement Function.prototype.call From Scratch in JavaScript
Implement Function.prototype.call from scratch in JavaScript by borrowing a method on the target object, with a Symbol key, primitives, apply and strict mode.

fn.call(thisArg, a, b) runs fn right now with this set to thisArg and the given arguments. To implement it without using call, apply or bind, you need a trick: the only way JavaScript sets this is by calling a function as a method of an object, so you temporarily attach the function to the target object and call it from there. This post builds that implementation on Node.js 24 in the order the interview goes: the basic idea, a collision-proof property key, primitive and missing targets, return values and the matching apply. It ends with what the trick cannot reproduce, and tests. The sibling question is implementing bind.
How this gets its value
When you write obj.method(), the engine calls method with this equal to obj. When you write method(), in strict mode, this is undefined. There is no other ordinary syntax that chooses this, apart from call, apply and bind themselves, and new. So an implementation of call has to arrange for the function to be a property of the object and then call it through that property.
The basic version
Function.prototype.myCall = function (context, ...args) {
const target = context ?? globalThis;
target.__fn__ = this;
const result = target.__fn__(...args);
delete target.__fn__;
return result;
};
function describe(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
console.log(describe.myCall({ name: "Ana" }, "Hello", "!"));Hello, I am Ana!Inside myCall, this is the function that .myCall was called on, describe. The code puts it on the target under the name __fn__, calls it with the arguments, removes it and returns the result. The call target.__fn__(...args) is a method call, so describe sees this equal to the target and reads this.name.
The context ?? globalThis line chooses a default when thisArg is null or undefined. In sloppy mode, the real call substitutes the global object. In strict mode, it passes null or undefined through unchanged. Our version always substitutes the global, which is the sloppy behavior, and the mismatch is one of the follow-ups.
Problem: the property name can collide
If the target already has a property named __fn__, the code overwrites it and then deletes it. Use a Symbol, which cannot collide with any existing string key.
Function.prototype.myCall = function (context, ...args) {
const target = context ?? globalThis;
const key = Symbol("fn");
target[key] = this;
try {
return target[key](...args);
} finally {
delete target[key];
}
};
const user = { name: "Bo", __fn__: "keep me" };
function whoami() {
return this.name;
}
console.log(whoami.myCall(user), user.__fn__);
console.log(Object.getOwnPropertySymbols(user).length);Bo keep me
0A fresh Symbol is unique, so the temporary property never clashes with anything, and it does not show up in Object.keys or for...in, though Object.getOwnPropertySymbols would see it while the call is running. The try and finally guarantee the cleanup even when the function throws, so a failing call does not leave a stray property behind.
function boom() {
throw new Error("failed");
}
try {
boom.myCall(user);
} catch (error) {
console.log(error.message, Object.getOwnPropertySymbols(user).length);
}failed 0Problem: primitives as this
If thisArg is a primitive, such as a number or a string, target[key] = this does nothing visible: assigning a property to a primitive silently fails in sloppy mode and throws a TypeError in strict mode, which module code always uses. The real call boxes primitives in sloppy functions and passes them as is in strict ones. Wrapping the primitive with Object() gives a boxed object and makes the assignment work.
Function.prototype.myCall = function (context, ...args) {
const target = context === null || context === undefined ? globalThis : Object(context);
const key = Symbol("fn");
Object.defineProperty(target, key, { value: this, configurable: true });
try {
return target[key](...args);
} finally {
delete target[key];
}
};
function typeOfThis() {
return typeof this;
}
console.log(typeOfThis.myCall(5), typeOfThis.myCall("text"), typeOfThis.myCall(null));
console.log(typeOfThis.call(5));object object object
numberThe primitive 5 is boxed into a Number object, so this is an object. The real call on a function in strict mode would give number, as the last line shows for a module, where the function is strict. This is a real difference, and it is the reason a faithful implementation cannot be written in plain code: whether this is boxed depends on the strictness of the target function, which no JavaScript code can read.
Defining the property with Object.defineProperty and configurable: true is slightly more robust than plain assignment, since it ignores setters on the prototype chain. It does not help with frozen targets: adding a property to a frozen object throws a TypeError in both forms.
const frozen = Object.freeze({ name: "Cy" });
try {
whoami.myCall(frozen);
} catch (error) {
console.log(error.name);
}
console.log(whoami.call(frozen));TypeError
CyThe real call has no problem with a frozen object, because it never adds a property. The temporary-property trick fundamentally needs a writable target. An honest answer says so, and notes that the trick is a teaching device and that the spec defines call directly through the internal [[Call]] operation.
Return values and arguments
The implementation returns whatever the function returns, and spreads the arguments as they were given.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, this.start);
}
console.log(sum.myCall({ start: 100 }, 1, 2, 3));
console.log(sum.myCall({ start: 0 }));106
0With no arguments after the context, args is an empty array, and the reduce returns the start value. call takes the arguments one by one, and apply takes them as an array, and that is the only difference between the two.
The matching apply
Function.prototype.myApply = function (context, args = []) {
if (args !== null && typeof args !== "object") {
throw new TypeError("CreateListFromArrayLike called on non-object");
}
return this.myCall(context, ...(args ?? []));
};
console.log(sum.myApply({ start: 10 }, [1, 2]));
console.log(sum.myApply({ start: 10 }));13
10apply accepts null or undefined for the list and treats it as empty, and throws a TypeError for other primitives. Real apply also accepts array-like objects such as arguments, and spreading a non-iterable array-like with ... would fail. To support them, convert with Array.from(args) first.
function viaArguments() {
return sum.myApply({ start: 0 }, arguments);
}
try {
console.log(viaArguments(1, 2));
} catch (error) {
console.log(error.name);
}3The arguments object is iterable, so the spread works here. A plain object with a length property and numbered keys, such as { 0: 1, 1: 2, length: 2 }, is array-like but not iterable, and would throw a TypeError with spread. Use Array.from(args) to handle both, since it accepts iterables and array-likes alike.
A cleaner answer using Reflect
If the interviewer allows built-ins other than call, apply and bind, Reflect.apply sets this directly and avoids all the problems above.
Function.prototype.myCall = function (context, ...args) {
return Reflect.apply(this, context, args);
};
console.log(describe.myCall({ name: "Di" }, "Hi", "?"));
console.log(typeOfThis.myCall(5), whoami.myCall(frozen));Hi, I am Di?
number CyReflect.apply(fn, thisArg, argList) is the specified operation behind Function.prototype.apply. It respects strict mode, handles primitives and frozen objects, and needs no temporary property. In an interview, the temporary-property version is what is expected when apply is banned, and Reflect.apply is the answer in a real code base. If you are ever tempted to use either, remember that the language already provides call.
How to present it
Open with the idea that makes the question solvable: this is chosen by the way a function is called, so to control it, call the function as a method of the object you want. Many candidates know the answer and cannot say why it works, and saying it first shows that you understand the mechanism and are not reciting a snippet.
Then list the weak points of your own code in the order of importance. A string key can collide with a real property, so use a Symbol. A throwing function can leave the property behind, so use finally. A primitive target cannot hold a property, so box it. And a frozen target cannot be used at all. If you can say the last one calmly, the interviewer learns that you know where the technique ends.
Finish by naming the practical answer. In real code you never write this function: call exists, and Reflect.apply exposes the same operation as a function. The exercise is useful because it makes you look at how method calls assign this, and that knowledge pays off every time a callback loses its receiver and you have to work out why.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("myCall sets this and passes arguments", () => {
function add(a, b) {
return this.base + a + b;
}
assert.equal(add.myCall({ base: 1 }, 2, 3), 6);
});
test("myCall leaves the target untouched", () => {
const target = { name: "x" };
(function () {}).myCall(target);
assert.deepEqual(Reflect.ownKeys(target), ["name"]);
});ℹ tests 2
ℹ pass 2
ℹ fail 0The second test checks the cleanup: after the call, the target has only its original key. Those two tests are for the temporary-property version, which is the one an interviewer wants to see; the Reflect.apply version passes them as well.


