← Daily Logs
GreatFrontEnd

Implement Function.prototype.bind

EasyJul 2, 2026javascriptthispolyfillclosures

The third leg of the `call`/`apply`/`bind` trio, and the one where an arrow function stops being the easy default. `bind` has to return something callable *later*, possibly with more arguments than were originally given — an arrow function with no parameters can't hold up its end of that.

The problem

Implement `Function.prototype.myBind(thisArg, ...argArray)` returning a new function that, when called, invokes the original with `this` set to `thisArg` and `argArray` prepended to whatever arguments the returned function is called with — `john.getAge.myBind(john)()` → `42`.

The behavior a naive version tends to miss: arguments passed to the *bound* function at call time must be appended after the preset ones, not dropped — `person.dummy.myBind(person, 2, 3)(5)` should still see all three.

The approach

`return () => this.apply(thisArg, argArray)` looks right but the returned function takes no parameters, so any arguments given to the bound function at call time are simply thrown away instead of being appended.

Declaring the inner function with its own rest parameter — `function (...callArgs) { ... }` — and merging with `[...argArray, ...callArgs]` fixes that: preset arguments first, call-time arguments after, exactly as MDN describes. Capturing `originalFn = this` before returning keeps the reference to the function being bound, since the inner function's own `this` no longer refers to it.

The solution

js
/**
 * @param {any} thisArg
 * @param {...*} argArray
 * @return {Function}
 */
Function.prototype.myBind = function (thisArg, ...argArray) {
  const originalFn = this;
  return function (...callArgs) {
    return originalFn.apply(thisArg, [...argArray, ...callArgs]);
  };
};

Time O(n)Space O(n)

All entries