Facebook Pixel

bind Polyfill: Step-by-Step Explanation

Detailed walkthrough of each step in the bind polyfill implementation.

bind Polyfill: Step-by-Step Explanation

Step 1: Return a Function

bind returns a new function. So our polyfill must return a function:

Function.prototype.myBind = function (context) { const fn = this; // the original function return function () { return fn.call(context); // call with the bound this }; };

this inside myBind is the function on which myBind is called (e.g., greet in greet.myBind(obj)).

Step 2: Pass Arguments

The returned function may receive arguments when called. Pass them through:

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

presetArgs are arguments passed to myBind (partial application). laterArgs are arguments passed when the bound function is called.

Step 3: Support new

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

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

this instanceof boundFn is true when called with new.

The Takeaway

Step by step: (1) return a function that calls the original with call(context), (2) pass preset and later arguments with rest/spread, (3) check this instanceof boundFn to support new. Each step builds on the previous one.

this is the function on which myBind is called. For greet.myBind(obj), this is greet. Store it: const fn = this, and use it in the returned function.

presetArgs are passed to myBind: greet.myBind(obj, 'Hello'). laterArgs are passed when the bound function is called: bound('!'). Both are spread into fn.call: fn.call(context, ...presetArgs, ...laterArgs).

To support the new operator. When a bound function is called with new, this should be the new instance, not the bound context. this instanceof boundFn is true only when called with new.

new boundFn() would set this to the bound context instead of a new instance. This is incorrect behavior. The real bind supports new, so the polyfill should too.

const bound = greet.myBind(obj, 'Hello'); console.log(bound('!')); should output 'Hello, Kunal!'. Test with: no args, preset args, later args, both, and new (if implemented).

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.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.