All questions

Function.prototype.bind

Premium

Function.prototype.bind

Implement Function.prototype.myBind — a from-scratch version of Function.prototype.bind. Given any function, fn.myBind(thisArg, ...preset) returns a new function whose this is permanently fixed to thisArg and whose argument list is prepended with preset before forwarding to the original.

This is the same feature the language uses for partial application — preset some arguments now, supply the rest at call time.

Signature

// Installed on Function.prototype.
fn.myBind(thisArg: any, ...preset: any[]): (...later: any[]) => any
//   ^ when the returned function is called with `later`, it invokes
//     fn.call(thisArg, ...preset, ...later)

Examples

function greet(greeting, name) {
  return `${greeting}, ${name}! I am ${this.role}.`;
}
const sayHiAsAdmin = greet.myBind({ role: 'admin' }, 'Hi');
sayHiAsAdmin('Ana'); // → "Hi, Ana! I am admin."
// The bound `this` cannot be overridden by .call/.apply on the result.
function whoAmI() { return this.name; }
const boundToA = whoAmI.myBind({ name: 'A' });
boundToA.call({ name: 'B' }); // → "A", not "B"
// Length reflects the remaining (un-preset) arity.
function add(a, b, c) { return a + b + c; }
add.length;                // 3
add.myBind(null, 1).length; // 2  (one arg already supplied)

Notes

  • this is locked — once a function is bound, .call, .apply, and re-bind on the result cannot change its this. This is the spec's most-missed detail.
  • Arguments are concatenated — preset args come first, call-time args come after, in that order.
  • length reflects remaining arity — the bound function's length is Math.max(0, fn.length - preset.length).
  • new is out of scope — you do NOT have to support new boundFn(...) correctly. A basic implementation can ignore it. (See Going further in the solution.)
  • Don't mutate fn — return a brand-new function; the original must keep working unchanged.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium