Skip to content
JavaScript utilities · Senior · about 15 minutes

Bind

Implement bind(fn, thisArg, ...partial) without Function.prototype.bind (the tests remove it). The returned function calls fn with this set to thisArg, with the partial arguments first and the call's own arguments after them. Calling the returned function as a method of another object must not change this. In the tests fn returns [this.name, ...arguments].

Start from

function bind(fn, thisArg, ...partial) {
  // Return a function that always calls fn with thisArg.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Return a function that collects its own arguments and uses fn.apply.

  2. Hint 2

    The partial arguments go before the new ones: fn.apply(thisArg, [...partial, ...args]).

Solution

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
function bind(fn, thisArg, ...partial) {
  return function (...args) {
    return fn.apply(thisArg, [...partial, ...args]);
  };
}

What an interviewer looks for

It proves you know how this is decided at the call site, and what call and apply do. The follow-up is what the real bind does when the bound function is called with new.