Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
return function bound(...args) {
if (new.target) return new fn(...preset, ...args);
return fn.apply(ctx, [...preset, ...args]);
};
};
bind must return a new function. That function calls the original with a fixed this. Preset arguments go first, then the arguments given at call time.
The steps in the code:
- Inside
myBind,thisis the function being bound, so save it asfn. - Return a new function that joins the preset arguments with the call-time arguments.
- Use
applyto call the original with the chosen context.
A complete version also handles new. When someone calls the bound function as a constructor, the bound this is ignored. A new instance of the original function is created instead. Checking new.target detects this case, because new.target is set only when a function is called with new.
The real bind also sets name to bound fn and adjusts length. Interviewers rarely ask for this.
- Save the original function, which is
thisinsidemyBind. - Return a closure that joins the preset arguments and the call-time arguments.
- Call the original with
apply(orcall) using the bound context. - Bonus: ignore the bound
thiswhen the function is called withnew.