HomePremium · ₹1199
← All questions

Implement Function.prototype.bind (myBind)

Medium
Asked at:MicrosoftUber
Was this asked in an interview?

Write myBind(fn, thisArg, ...boundArgs) — return a new function permanently bound to thisArg, supporting partial application.

Problem

Implement myBind(fn, thisArg, ...boundArgs) — a standalone version of Function.prototype.bind.

Unlike call/apply, bind does not invoke the function. It returns a new function whose this is locked to thisArg forever, optionally with some leading arguments pre-filled (partial application). This is the classic fix for "losing this" when passing a method as a callback (e.g. onClick={this.handleClick.bind(this)}).

Your myBind(fn, thisArg, ...boundArgs) must:

  • Return a new function.
  • When that function is later called with ...callArgs, invoke fn with this = thisArg and arguments [...boundArgs, ...callArgs].
  • Keep the this binding permanent — calling it as a method on another object must not change this.

Input

function multiply(a, b, c) {
  return a * b * c;
}
const double = myBind(multiply, null, 2); // pre-fill a = 2
double(3, 4);

Expected output

24

Implement from scratch:

function myBind(fn, thisArg, ...boundArgs) {
  // Your code here
}
Implement Function.prototype.bind (myBind) — JavaScript Interview Question | Mentoxis