Function.prototype.bind
JS Functions
Medium
20 min
this
functions
polyfills
closures
prototypes
Implement Function.prototype.myBind(thisArg, ...boundArgs), a polyfill for Function.prototype.bind. It returns a new function that, when called, invokes the original with this fixed to thisArg and boundArgs prepended to the call's own arguments.
The starter attaches the function to Function.prototype and default-exports it.
const user = { name: 'Grace' };
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const hello = greet.myBind(user, 'Hello');
hello('!'); // 'Hello, Grace!'
hello.call({ name: 'Other' }, '?'); // 'Hello, Grace?' (bound `this` wins)
function Point(x, y) {
this.x = x;
this.y = y;
}
const AtOrigin = Point.myBind(null, 0);
const p = new AtOrigin(5); // Point { x: 0, y: 5 }
p instanceof Point; // true
p instanceof AtOrigin; // true
Requirements
- Throw a
TypeErrorifmyBindis called on a non-function. - Calling the bound function invokes the target with the bound
thisand[...boundArgs, ...callArgs], and returns its result.call/apply/bindon the bound function cannot changethis. - Calling with
new: the boundthisis ignored. The target is constructed with the combined arguments, and the result is an instance of the target.instance instanceof boundFnis alsotrue. - Binding a bound function again keeps the first
this, and the bound arguments accumulate. - The bound function's
nameis'bound ' + target.name, and itslengthis the target's length minus the number of bound arguments (never below 0). - You may use
Reflect.applyandReflect.construct(orapply) inside the bound function. Do not use the nativebind.
Follow-up
- Why does
thisget lost insetTimeout(obj.method, 0)or<button onClick={this.handleClick}>, and how doesbindfix it? - Arrow functions vs
bind: what are the trade-offs?
Spotted a mistake or a rights concern? Report an issue