Hiprup

How do you implement bind from scratch?

bind returns a new function with this permanently set and optional preset arguments.

The approach:

  1. Return a new function that closes over the target function and the desired this.

  2. Inside, call the original with that fixed this using apply.

  3. Combine the preset arguments with any new ones passed at call time (partial application).

Edge case: a bound function used with new should still work as a constructor — advanced implementations handle that.

Function.prototype.myBind = function(thisArg, ...boundArgs) {
  const fn = this; // The original function

  return function(...callArgs) {
    return fn.apply(thisArg, [...boundArgs, ...callArgs]);
  };
};

// Test
const user = { name: 'John' };

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const greetJohn = greet.myBind(user, 'Hello');
console.log(greetJohn('!'));   // 'Hello, John!'
console.log(greetJohn('?'));   // 'Hello, John?'

// Partial application
const add = (a, b, c) => a + b + c;
const add5 = add.myBind(null, 5);    // Pre-fill first arg
console.log(add5(3, 2));             // 10 (5 + 3 + 2)

const add5and3 = add.myBind(null, 5, 3); // Pre-fill first two
console.log(add5and3(2));            // 10 (5 + 3 + 2)

myBind saves the original function (fn = this) and pre-filled arguments (boundArgs). It returns a new function that, when called, applies fn with the bound this and combined arguments (pre-filled + new).

Partial application: greet.myBind(user, 'Hello') pre-fills this and the first argument.

This is a classic advanced coding question. Key parts: save the original function, return a new function, use apply to set this and combine arguments.

The partial application aspect (pre-filling arguments) must work correctly. Note: this simplified version does not handle the new operator — mention this limitation.

How do you implement bind from scratch? | Hiprup