QuestionsJavaScript

Implement Function.prototype.bind

Implement from scratchMediumJavaScript

Implement your own bind, and explain how it relates to call and apply.

What it tests

Deep understanding of `this` binding, partial application, and function invocation.

Approach & answer

call and apply invoke a function immediately with an explicit `this`: call takes arguments individually, apply takes them as an array. bind does not invoke — it returns a new function that, when later called, runs the original with the bound `this` and any pre-filled (curried) leading arguments, concatenated with the arguments passed at call time. A faithful polyfill also handles being called as a constructor with `new`: in that case the bound `this` must be ignored and the newly-created instance used instead, while the prototype chain is preserved. Signal to reach for bind: fixing `this` for a detached callback (React class handlers, setTimeout), or partial application. Modern code often replaces bind with arrow functions (which capture `this` lexically) for callbacks.

Use this technique when

Partial application, fixing `this` for callbacks, and understanding legacy class-component handlers.

References

js