Function.prototype.call
JS Functions
Medium
15 min
this
functions
polyfills
symbols
Implement Function.prototype.myCall(thisArg, ...args), a polyfill for Function.prototype.call. It invokes the function with this set to thisArg and the remaining arguments passed individually, and returns the function's result.
The starter attaches the function to Function.prototype and default-exports it.
function describe(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
describe.myCall({ name: 'Ada' }, 'Hello', '!'); // 'Hello, Ada!'
function add(a, b) {
return a + b;
}
add.myCall(null, 2, 3); // 5
Requirements
- Do not use
call,apply,bindorReflect.apply. The point is to make the engine setthisfor you through a method call (obj.fn()). - Throw a
TypeErrorifmyCallis invoked on something that is not a function. - Primitive
thisArgvalues are wrapped in their object form (sothis.toFixedworks whenthisArgis2). AnullorundefinedthisArgmeansglobalThis. - Any temporary property you add to
thisArgmust not collide with existing properties and must be removed afterwards, even if the function throws. - Errors thrown by the function propagate to the caller.
Clarification
The native call passes primitives and null/undefined through untouched to strict-mode functions. A userland polyfill can't do that with the method-call trick, so the boxing and globalThis rules above describe the sloppy-mode behaviour, which is what this exercise targets. Explain the limitation in your answer.
Follow-up
- What happens if
thisArgis a frozen object? - How is
calldifferent fromapplyandbind?
Spotted a mistake or a rights concern? Report an issue