CodePark/ problems / bind
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › this, call/apply/bind and prototypes

bind

hardabout 30 minutes in an interview

Implement myBind(fn, thisArg, ...boundArgs). It returns a new function. When you call that new function, it runs fn with this set to thisArg. The arguments are boundArgs followed by the arguments of the call. It returns whatever fn returns.

  • this stays fixed. Calling the result as a method of another object, or binding it again, doesn't change it.
  • The result also works with new. In that case thisArg is ignored and fn runs as a constructor. The result is a new object that passes instanceof fn and has the methods on fn.prototype. If fn returns an object, new gives that object instead.
  • Don't use Function.prototype.bind, and don't modify Function.prototype. You may use call or apply.
  • If fn is not a function, throw a TypeError.
Input: const hi = myBind(function (g, p) { return g + ' ' + this.name + p; }, { name: 'Ada' }, 'Hi'); hi('!') Output: 'Hi Ada!'
Input: function P(x, y) { this.x = x; this.y = y; } const P3 = myBind(P, { z: 1 }, 3); new P3(4) Output: { x: 3, y: 4 }, an instance of Pwith new, the bound this { z: 1 } is ignored