Problem
Implement myBind(fn, thisArg, ...boundArgs) — a standalone version of Function.prototype.bind.
Unlike call/apply, bind does not invoke the function. It returns a new function whose this is locked to thisArg forever, optionally with some leading arguments pre-filled (partial application). This is the classic fix for "losing this" when passing a method as a callback (e.g. onClick={this.handleClick.bind(this)}).
Your myBind(fn, thisArg, ...boundArgs) must:
- Return a new function.
- When that function is later called with
...callArgs, invokefnwiththis = thisArgand arguments[...boundArgs, ...callArgs]. - Keep the
thisbinding permanent — calling it as a method on another object must not changethis.
Input
function multiply(a, b, c) {
return a * b * c;
}
const double = myBind(multiply, null, 2); // pre-fill a = 2
double(3, 4);
Expected output
24
Implement from scratch:
function myBind(fn, thisArg, ...boundArgs) {
// Your code here
}