CodePark/ questions / this & binding
START PRACTICINGPRACTICE
Frontend question · JavaScript › this & binding

Implement your own version of Function.prototype.bind.

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, this is the function being bound, so save it as fn.
  • Return a new function that joins the preset arguments with the call-time arguments.
  • Use apply to 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 this inside myBind.
  • Return a closure that joins the preset arguments and the call-time arguments.
  • Call the original with apply (or call) using the bound context.
  • Bonus: ignore the bound this when the function is called with new.