QuestionsJavaScript

Polyfill Function.prototype.call & apply

Polyfills / this bindingMediumJavaScript

Implement call and apply from scratch. How do you invoke a function with an explicit `this` without using call/apply/bind?

What it tests

The core trick: a function called as a METHOD gets its object as `this` — so temporarily attach the fn to the target, invoke, then clean up.

Approach & answer

The insight is that JavaScript's implicit `this` binding does the work for you: when you call `obj.fn()`, `this` inside fn IS obj. So to force a function to run with an arbitrary `this`, you TEMPORARILY make it a property of that object, call it as a method, then remove the property. `call` takes the this-arg then individual arguments; `apply` is identical except it takes an array of arguments. Robust details: (1) coerce the this-arg — null/undefined should become globalThis (non-strict semantics), and primitives should be boxed via Object(thisArg) so the property assignment works. (2) Use a unique Symbol as the temporary key so you never collide with or clobber a real property on the target object. (3) Wrap the invocation in try/finally and `delete` the temp key in finally, so you clean up even if the function throws. (4) Return the function's result. Once you have call, apply is a one-liner (`this.call(thisArg, ...args)`) and vice versa — they're duals. This is the mechanism behind method borrowing (e.g. `Array.prototype.slice.call(arguments)`), and it's the foundation bind builds on (bind returns a new function that internally applies the saved this-arg and partial args).

Use this technique when

Explaining how `this` binding is implemented, method borrowing, and building bind/partial-application from first principles.

Complexity

O(1) overhead plus the wrapped call.

References

js