← Back to JavaScript, page 5

javascript-0084 · Medium mid

How would you implement Function.prototype.bind yourself, including partial arguments and use with new?

bind returns a new function that calls the original with a fixed this and any pre-filled leading arguments followed by the new arguments. A faithful version also lets the bound function be used with new, in which case the fixed this is ignored and the new object inherits from the original function's prototype. The result should also keep a sensible length and name.

Full answer

bind(thisArg, ...fixedArgs) returns a new function. When the new function is called with ...laterArgs, it calls the original with this set to thisArg and the arguments [...fixedArgs, ...laterArgs].

The simple version is a closure that calls original.apply(thisArg, [...fixedArgs, ...laterArgs]). It covers most interview needs, but a complete version handles more.

When a bound function is called with new, the engine ignores the bound this. The new object should be created from the original function's prototype, so instance instanceof Original is true and instance instanceof Bound is also true. The implementation detects this with new.target (or this instanceof Bound in older code), and constructs with Reflect.construct(original, args, new.target).

Other details: throw a TypeError if the method is called on something that is not a function. The native bound function has no prototype property, and a polyfill usually points its own prototype at the original's so that instanceof works. Its length is the original length minus the number of fixed arguments (not below zero), and its name is "bound " plus the original name. A bound function cannot be rebound to a different this, which follows naturally because the closure always uses the stored thisArg.

Arrow functions ignore thisArg, as they have no this, but they can still have arguments pre-filled by bind.

The bind method is also the simplest way to create partially applied functions, which links the topic to currying.

javascript
function myBind(original, thisArg, ...fixedArgs) {
  if (typeof original !== 'function') throw new TypeError('Bind must be called on a function');
  function bound(...laterArgs) {
    const args = [...fixedArgs, ...laterArgs];
    if (new.target) return Reflect.construct(original, args, new.target === bound ? original : new.target);
    return original.apply(thisArg, args);
  }
  bound.prototype = original.prototype; // lets instanceof work; native bound functions have no prototype property
  Object.defineProperty(bound, 'name', { value: `bound ${original.name}`, configurable: true });
  Object.defineProperty(bound, 'length', { value: Math.max(0, original.length - fixedArgs.length), configurable: true });
  return bound;
}

function introduce(greeting, punctuation) {
  return `${greeting}, I am ${this.name}${punctuation}`;
}
const person = { name: 'Asha' };
const bound = myBind(introduce, person, 'Hello');
console.log(bound('!'), introduce.bind(person, 'Hello')('!'));
console.log(bound.name, bound.length, introduce.bind(person, 'Hello').name, introduce.bind(person, 'Hello').length);

const rebound = myBind(bound, { name: 'Ravi' }, '?');
console.log(rebound());

function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.sum = function () {
  return this.x + this.y;
};
const BoundPoint = myBind(Point, { ignored: true }, 10);
const point = new BoundPoint(5);
console.log(point.x, point.y, point.sum(), point instanceof Point, point instanceof BoundPoint);
const NativeBound = Point.bind({ ignored: true }, 10);
const nativePoint = new NativeBound(5);
console.log(nativePoint.sum(), nativePoint instanceof Point, nativePoint instanceof NativeBound, Object.hasOwn(NativeBound, 'prototype'));

const counter = {
  count: 0,
  add() {
    this.count += 1;
    return this.count;
  },
};
const detachedAdd = myBind(counter.add, counter);
const handlers = [detachedAdd, detachedAdd];
console.log(handlers.map((fn) => fn()));

const arrow = () => typeof this;
console.log(myBind(arrow, { x: 1 })());
try {
  myBind('not a function', {});
} catch (error) {
  console.log(error.name);
}

Run with Node.js v24.22.1 as js-84.js; two runs gave identical output. Output: Hello, I am Asha! Hello, I am Asha! bound introduce 1 bound introduce 1 Hello, I am Asha? 10 5 15 true true 15 true true false [ 1, 2 ] object TypeError

Key points

  • bind returns a closure that applies the original with a stored this and pre-filled arguments.
  • Later arguments are appended after the fixed ones.
  • With new, the bound this is ignored and the original constructor is used.
  • Detect construction with new.target and build with Reflect.construct.
  • Bound functions are named "bound x", have a reduced length, and cannot be rebound.

Common mistakes

  • Ignoring new, so the bound constructor creates objects with the wrong prototype.
  • Forgetting to append the later arguments after the fixed ones.
  • Using the arguments object with arrow functions inside the implementation.
  • Letting a second bind change this on an already bound function.

Follow-ups

  • How does new.target differ from this instanceof Bound for detecting construction?
  • Why does a bound function not have a prototype property?
  • How would you implement call and apply from scratch?

Tips

  • Write the simple closure first and then volunteer the new-support extension.
  • Mention name and length to show attention to the specification.
  • Connect bind to partial application.