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.
thisstays 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 casethisArgis ignored andfnruns as a constructor. The result is a new object that passesinstanceof fnand has the methods onfn.prototype. Iffnreturns an object,newgives that object instead. - Don't use
Function.prototype.bind, and don't modifyFunction.prototype. You may usecallorapply. - If
fnis not a function, throw aTypeError.
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