Implement myBind(fn, thisArg, ...boundArgs)
The interview classic. Write myBind(fn, thisArg, ...boundArgs) that returns a new function which, when called:
- Invokes
fnwiththisbound tothisArg. - Prepends
boundArgsbefore whatever arguments the new function is called with (partial application). - New-safety: if the bound function is itself called with
new, the presetthisArgmust be ignored, a fresh object should be constructed as normal, and it must still be aninstanceofthe originalfn.
function add(a, b, c) { return a + b + c; }
const add5 = myBind(add, null, 5);
add5(1, 2); // 8
function Point(x, y) { this.x = x; this.y = y; }
const BoundPoint = myBind(Point, { x: 999 });
new BoundPoint(3, 4).x; // 3, the preset thisArg was ignored