Write your own version of Function.prototype.bind.
Add a method on Function.prototype that remembers the original function, the chosen this and any preset arguments, and returns a new function that calls the original with apply, joining preset and new arguments.
Explain it simply
To write bind you only need two ideas you already know. First, inside a method added to Function.prototype, this is the function you are binding. Second, a closure can remember the chosen context and the preset arguments.
The returned function, when called later, uses apply to run the original with the saved context, putting the preset arguments first and the new ones after.
This version leaves out the new edge case, which a full polyfill also handles.
Line by line
Function.prototype.myBind = function (context, ...preset) {
const fn = this;
return function (...later) {
return fn.apply(context, [...preset, ...later]);
};
};
function add(a, b) {
return this.base + a + b;
}
const addTen = add.myBind({ base: 10 }, 1);
console.log(addTen(2)); // Output: 13
console.log(addTen(5)); // Output: 16What to say in the interview
"bind returns a new function. I capture the target function, the context and the preset arguments in a closure, then on call run fn.apply(context, preset.concat(later)). A complete polyfill also respects new, where the bound this is ignored."
Complexity
Time O(1) to bind, O(k) per call for k total arguments. Space O(k) for the saved arguments.
Common mistakes
- Using this inside the returned function expecting it to be the original function. Save it first as fn.
- Forgetting to merge preset and later arguments.