Implement Function.prototype.bind
Write a polyfill myBind that returns a new function with `this` permanently bound to a given context and support for partial application. This is a deep test of `this`, closures, and the prototype chain — the new-operator edge case is the classic follow-up.
Examples
Input: greet.myBind(person, "Hello")("!") where greet uses this.name
Output: "Hello, Ada!"
// `this` is fixed to person; "Hello" is a preset arg, "!" is supplied later.
Input: new (Point.myBind(null, 10))(20)
Output: Point { x: 10, y: 20 }, instanceof Point === true
// When called with `new`, the bound context is ignored and the prototype chain is preserved.
Constraints
- Return a new function; do not invoke the original immediately.
- Support partial application of leading arguments.
- Bonus: when used with `new`, ignore the bound `this` and preserve the prototype chain.
prototypethisclosurepolyfill
Important
Interview Tip
Capture the original function as `const fn = this`, then return a closure that does fn.apply(context, presetArgs.concat(laterArgs)). The senior follow-up is the `new` case — detect `this instanceof bound` and reset the prototype with Object.create(fn.prototype). Know call/apply/bind cold.
Approach: Core Polyfill
Capture the function, return a closure that applies it with the bound context and merged args. The standard answer.
Complexity
Time: O(1)Space: O(1)
Pros
- Fixes `this` correctly
- Supports partial application
- Short and clear
Cons
- Breaks when the bound function is used with `new`
- Does not preserve the prototype chain