Learn the concept
The this Keyword
A bind polyfill returns a new function that calls the original with a fixed `this` context and optionally prepended arguments. The implementation must handle partial application, preserve the prototype chain when used with `new`, and forward all arguments correctly.
Implementing Function.prototype.bind from scratch is a common interview question at companies like Swiggy and Flipkart. It tests deep understanding of this binding, closures, argument handling, and the new operator.
bind(thisArg, ...args) returns a new function where:
this is permanently set to thisArgargs) are baked in (partial application)new, the thisArg is ignored and the new object becomes thisapply or call to set thisnew operator support — Detect when the bound function is called with new and skip the forced this binding. The returned object should inherit from the original function's prototype.instanceof works correctlythis instanceof boundFn? This detects whether the bound function was called with new. When new boundFn() is used, this is a new object whose prototype is boundFn.prototype, making this instanceof boundFn true.Object.create for the prototype? Using boundFn.prototype = originalFn.prototype would create a shared reference — modifying the bound function's prototype would also modify the original's. Object.create creates a separate object that inherits from the original prototype.this binding and no prototype property. bind returns a function, but the this override has no effect since arrow functions capture this lexically.Function.prototype.myBind = function (thisArg, ...boundArgs) {
if (typeof this !== 'function') {
throw new TypeError('myBind must be called on a function');
}
const originalFn = this;
return function boundFn(...callArgs) {
// Merge bound args with call-time args
return originalFn.apply(thisArg, [...boundArgs, ...callArgs]);
};
};
// Usage
const greet = function (greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
};
const greetAlice = greet.myBind({ name: 'Alice' }, 'Hello');
console.log(greetAlice('!')); // 'Hello, Alice!'
console.log(greetAlice('?')); // 'Hello, Alice?'React class components use bind in constructors to preserve `this` context when methods are passed as event callbacks.
Creating pre-configured functions using bind to fix certain parameters, such as a logger bound to a specific module name.
Implement call, apply, and bind from scratch with full spec compliance including Symbol.hasInstance and proper length/name properties.