Implement bind
You pass an object's method to setTimeout, and when it runs the object is gone
and this is undefined. The method needed its receiver, but calling it bare
dropped the receiver. You want to hand the function off with its this already
fixed — and maybe with its first arguments locked in too.
bind returns a new function that always runs the original with a fixed
this, and it can prepend arguments captured at bind time.
The shape closes over the function, the receiver, and the bound arguments:
function bind(fn, thisArg, ...boundArgs) {
return (...callArgs) => fn.apply(thisArg, [...boundArgs, ...callArgs]);
}
The returned function runs fn with apply, passing thisArg as this and
concatenating the arguments captured at bind time with the arguments given at
call time. fn.call(...) would work too; apply is used because the arguments
arrive as an array. The bound arguments come first, then the call's own — so
bind(greet, person, 'Hello')('!') runs greet with this set to person and
the arguments 'Hello' then '!'.
Export bind from index.js. Your job is to fix this and prepend the bound
arguments.
Challenge
A method passed to setTimeout runs with its object gone and this undefined.
Export a bind function from index.js to hand the function off with this
fixed.
bind takes a function, a thisArg, and any number of partial arguments, and
returns a new function. Calling the returned function runs the original with
this set to thisArg, passing the arguments bound first, followed by the
arguments given at call time.