Facebook Pixel

How to Write a Polyfill for bind in JavaScript

Implementing bind from scratch is a common interview question. Here is the step-by-step implementation.

How to Write a Polyfill for bind in JavaScript

Writing a polyfill for bind is a common interview question. Here is the step-by-step implementation.

What bind Does

bind returns a new function with this permanently bound and optional preset arguments.

Step 1: Basic Implementation

Function.prototype.myBind = function (context) { const fn = this; return function () { return fn.call(context); }; };

Step 2: Support Preset Arguments

Function.prototype.myBind = function (context, ...presetArgs) { const fn = this; return function (...laterArgs) { return fn.call(context, ...presetArgs, ...laterArgs); }; };

Step 3: Support new Operator

When a bound function is called with new, this should be the new object, not the bound context:

Function.prototype.myBind = function (context, ...presetArgs) { const fn = this; const boundFn = function (...laterArgs) { const isNew = this instanceof boundFn; return isNew ? new fn(...presetArgs, ...laterArgs) : fn.call(context, ...presetArgs, ...laterArgs); }; boundFn.prototype = Object.create(fn.prototype); return boundFn; };

Testing

function greet(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`; } const obj = { name: "Kunal" }; const bound = greet.myBind(obj, "Hello"); console.log(bound("!")); // "Hello, Kunal!"

The Takeaway

bind polyfill: return a function that calls the original with call(context, ...presetArgs, ...laterArgs). Support preset arguments with rest/spread. Support new by checking this instanceof boundFn. Set boundFn.prototype for the prototype chain.

Function.prototype.myBind = function(context, ...presetArgs) { const fn = this; return function(...laterArgs) { return fn.call(context, ...presetArgs, ...laterArgs); }; }.

Use rest parameters: myBind = function(context, ...presetArgs). Spread them in the call: fn.call(context, ...presetArgs, ...laterArgs). This merges preset and later arguments.

Check this instanceof boundFn. If true (called with new), use new fn(...args) instead of fn.call(context, ...args). Set boundFn.prototype = Object.create(fn.prototype).

So that instances created with new boundFn() have the correct prototype chain. Without it, instanceof checks would fail. Set boundFn.prototype = Object.create(fn.prototype).

Basic: just sets this. Advanced: supports preset arguments (partial application) and the new operator (this is the new object when called with new, not the bound context).

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.