Implement Function.prototype.bind

hard
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement a deliberately scoped myBind(fn, thisArg, ...boundArgs) exercise. It must bind this for ordinary calls, support partial application, and support new for classic function constructors whose prototype is an object. Constructor calls must be detected with new.target, not by inspecting the receiver. This helper is not a complete Function.prototype.bind polyfill: ES classes, constructors that depend on new.target, bound-function exotic behavior, and native name, length, prototype, and Symbol.hasInstance semantics are outside the contract.

Arguments

  • fn: Function — The target function to bind.
  • thisArg: any — The this value to bind for normal calls (ignored when called with new).
  • boundArgs: any[] — Arguments to pre-apply to the function (partial application).

Returns

Function — A wrapper with bound-call and partial-application behavior plus the documented classic-constructor subset.

Solution idea

Goal: model the core call binding, partial arguments, and classic function-constructor behavior without claiming full native equivalence.

Examples
// Example 1: bind `this`
function getX() { return this.x; }
const obj = { x: 42 };
const bound = myBind(getX, obj);
bound(); // => 42

// Example 2: partial application
function add(a, b, c) { return a + b + c; }
const add5 = myBind(add, null, 2, 3);
add5(10); // => 15

// Example 3: `new` must ignore thisArg
function Person(name) { this.name = name; }
Person.prototype.say = function() { return this.name; };
const BoundPerson = myBind(Person, { name: 'SHOULD_NOT_USE' });
const p = new BoundPerson('Ada');
p.name; // => 'Ada'
p.say(); // => 'Ada'
p instanceof Person; // => true
p instanceof BoundPerson; // => true