Implement Function.prototype.bind, including new
Writing a bind that fixes this and prepends arguments takes three lines. The reason this is an interview favourite is the other half of the spec: a bound function used as a constructor must ignore the bound receiver entirely, because new supplies its own this, and instances must still be instanceof the original function.
Implement myBind(fn, thisArg, ...boundArgs), where fn is an ordinary function declared with the function keyword. It returns a new function that, when called normally, invokes fn with this set to thisArg and with boundArgs followed by the call-time arguments, returning fn's result. The bound receiver wins permanently: calling the bound function as a method of some other object does not change this inside fn. When the bound function is called with new, thisArg is ignored and this inside fn is the newly constructed object; boundArgs are still prepended, the result is the new object (assuming fn returns nothing), the object inherits from fn.prototype so methods defined there are available, and instance instanceof fn is true. Your implementation must not use Function.prototype.bind, call or apply: one of the tests replaces all three with functions that throw.
What it has to do
- Set
thistothisArgfor a normal call and prependboundArgs. - Keep the bound receiver even when the bound function is called as another object's method.
- Under
new, ignorethisArgand use the freshly constructed object asthis. - Under
new, keepfn.prototypein the instance's prototype chain soinstance instanceof fnholds and prototype methods work. - Work when
Function.prototype.bind,callandapplyhave been replaced with throwing stubs.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.