Prototypes & OOPmedium

Implement Function.prototype.bind

Implement your own version of `Function.prototype.bind`. It should return a new function with `this` permanently bound and support partial application. Bonus: handle `new` correctly.

Asked at TikTok, Apple, Meta

#this#prototype#bind#new

Answer

Function.prototype.myBind = function(thisArg, ...boundArgs) {
  const fn = this  // the original function

  return function bound(...callArgs) {
    // When used with 'new', ignore the bound 'this'
    if (new.target) {
      return new fn(...boundArgs, ...callArgs)
    }
    return fn.apply(thisArg, [...boundArgs, ...callArgs])
  }
}

// Usage
function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`
}

const user = { name: 'Alice' }
const sayHi = greet.myBind(user, 'Hello')
sayHi('!')   // "Hello, Alice!"
sayHi('?')   // "Hello, Alice?"

Source: frontendinterviewhandbook.com

Practise more Prototypes & OOP questions →