Q14: Implement a polyfill for Function.prototype.bind().

Difficulty:IntermediateTopic:Function Methods

Answer

The bind() method returns a new function that, when called, invokes the original function with a predetermined this value and optionally prepended arguments.

Function.prototype.myBind = function (thisArg, ...boundArgs) {
  if (typeof this !== "function") {
    throw new TypeError("myBind must be called on a function");
  }

  const originalFunction = this;

  function boundFunction(...laterArgs) {
    const isConstructing = new.target !== undefined;
    const receiver = isConstructing ? this : thisArg;

    return originalFunction.apply(receiver, [
      ...boundArgs,
      ...laterArgs
    ]);
  }

  if (originalFunction.prototype) {
    boundFunction.prototype = Object.create(originalFunction.prototype);
    Object.defineProperty(boundFunction.prototype, "constructor", {
      value: boundFunction,
      writable: true,
      configurable: true
    });
  }

  return boundFunction;
};

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

const person = { name: "Suriya" };
const sayHello = introduce.myBind(person, "Hello");

console.log(sayHello("!"));
// Hello, Suriya!

Explanation

  • boundArgs contains arguments provided when myBind() is called.
  • laterArgs contains arguments supplied when the bound function is invoked.
  • The bound function combines both argument lists.
  • When the bound function is invoked as a constructor using new, the new instance becomes the receiver rather than the bound thisArg.

Advanced limitation

A fully compliant native bind() also handles bound-function length and name properties, constructor behavior, and prototype semantics precisely. The implementation above demonstrates the central interview concept but does not reproduce every native edge case.

Partial application
function multiply(a, b, c) {
  return a * b * c;
}

const multiplyByTwo = multiply.myBind(null, 2);
console.log(multiplyByTwo(3, 4)); // 24
💡 Bind can preconfigure arguments as well as a receiver. This is called partial application.
Key Takeaways
  • Bind returns a new function instead of invoking the original immediately.
  • Bound arguments are prepended to arguments passed later, and construction requires special handling.