JS Machine Coding Questions — Implementations You Must Know
Custom bind
- Implement Function.prototype.myBind(ctx, ...presetArgs) — returns a new function with this bound to ctx and optional pre-filled arguments.
- Key insight: Return a closure. Inside, use apply to call the original function with the bound this. Merge preset args with new call-time args.
- Gotcha: this inside myBind is the function it's called on — save it before the returned closure shadows it.
- Gotcha: Real bind also handles new — when the bound function is used as a constructor, the bound this is ignored. Handle with instanceof.
1// Simple version
2Function.prototype.myBind = function (ctx, ...presetArgs) {
3 const fn = this;
4 return function (...callArgs) {
5 return fn.apply(ctx, [...presetArgs, ...callArgs]);
6 };
7};
8
9// With new support
10Function.prototype.myBind = function (ctx, ...presetArgs) {
11 const fn = this;
12 function bound(...callArgs) {
13 return fn.apply(
14 this instanceof bound ? this : ctx,
15 [...presetArgs, ...callArgs]
16 );
17 }
18 bound.prototype = Object.create(fn.prototype);
19 return bound;
20};