Javascript Fundamentals · Interview Challenges

Implement bind

bind

Implement bind

You pass an object's method to setTimeout, and when it runs the object is gone and this is undefined. The method needed its receiver, but calling it bare dropped the receiver. You want to hand the function off with its this already fixed — and maybe with its first arguments locked in too.

bind returns a new function that always runs the original with a fixed this, and it can prepend arguments captured at bind time.

The shape closes over the function, the receiver, and the bound arguments:

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

The returned function runs fn with apply, passing thisArg as this and concatenating the arguments captured at bind time with the arguments given at call time. fn.call(...) would work too; apply is used because the arguments arrive as an array. The bound arguments come first, then the call's own — so bind(greet, person, 'Hello')('!') runs greet with this set to person and the arguments 'Hello' then '!'.

Export bind from index.js. Your job is to fix this and prepend the bound arguments.

Challenge

A method passed to setTimeout runs with its object gone and this undefined. Export a bind function from index.js to hand the function off with this fixed.

bind takes a function, a thisArg, and any number of partial arguments, and returns a new function. Calling the returned function runs the original with this set to thisArg, passing the arguments bound first, followed by the arguments given at call time.

index.js
export function bind(fn, thisArg, ..._boundArgs) {
  return (...callArgs) => fn.apply(thisArg, callArgs);
}

export function render(mount) {
  const person = { name: 'Ada' };

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

  const greetAda = bind(greet, person, 'Hello', 'dear');

  const line = document.createElement('p');
  line.textContent = greetAda('!');
  mount.replaceChildren(line);
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.