bind Polyfill Common Mistakes
Common mistakes when writing a bind polyfill and how to fix them.
bind Polyfill Common Mistakes
Mistake 1: Not Returning a Function
bind must return a function. Forgetting the return function is common.
Mistake 2: Not Storing this
this inside the returned function is different. Store it: const fn = this.
Mistake 3: Not Passing Arguments
Forgetting to pass laterArgs or presetArgs through to the original function.
Mistake 4: Not Supporting new
The real bind supports new. Check this instanceof boundFn.
Mistake 5: Using Arrow Function for the Returned Function
Arrow functions do not have this, so this instanceof boundFn would not work. Use a regular function.
The Takeaway
Mistakes: not returning a function, not storing this (const fn = this), not passing arguments (presetArgs + laterArgs), not supporting new (instanceof check), and using an arrow for the returned function (arrows do not have this). Fix each for a correct polyfill.
Because this inside the returned function is different from this inside myBind. Store it: const fn = this. Use fn in the returned function. Without this, the polyfill cannot call the original function.
Because arrow functions do not have their own this. The instanceof check (this instanceof boundFn) would not work with arrows. Use a regular function for the returned function.
The original function would not receive the arguments passed when the bound function is called. For greet.myBind(obj, 'Hello')('!'), the '!' would be lost. Always spread laterArgs: fn.call(context, ...presetArgs, ...laterArgs).
Because the real bind supports new. If a bound function is called with new, this should be the new instance, not the bound context. Without new support, new boundFn() would incorrectly use the bound context as this.
Not storing this. Inside the returned function, this is not the original function. You must store it before returning: const fn = this. Then use fn.call(context) inside the returned function.
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.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

