Polyfill for bind() method in JavaScript

How to make a polyfill for bind method in javaScript

  idkblogs.com      July 27, 2021

Shubham Verma

Shubham Verma


Polyfill for bind() method in JavaScript

Polyfill for bind() method in javaScript

Polyfill is a browser fallback. If your browser don't have the bind() and you have to write your own bind() function, that is what we are going to do here.
So, let's impolement our own bind() function.
Let's have a look of actual bind():

The above code is actual bind that we need to implement our own bind.

Observation:

1. The above code has bind() method which is predefined. we need to create mybind() that will work same as bind() does.

2. printN.bind() is possible then printN.mybind() should be possible, but we need to declare with Function.prototype.mybind().

3. It will return a function, so our mybind() should return a function.

4. let printMyN2=print.mybind(name); and when we call printMyN2(), it should call printN() method with it's this.
So, how we'll get the printN() inside mybind()? we can get this by using this variable.
Inside mybind(),this refers to printN(). this->printN() . So we'll get by let obj=this && obj.call().

5. Now we need to name arguments in mybind().

Let's code:


We have done, but the problem is not solved-
If we also want hometown in printN(), then?
let's see.

So, to get this output, we need to change our code:

Is it done? No, the problem is not yet solved ;(
What if I need to add 'state' of the city.


So, let's fix this:



Now all set, this will work fine for our mybind().

Conclusion:

We have learned how we can create our own polyfill for those methods which is not supported by the browsers.


Thank you

for taking the time to read this article. If you’re interested in Node.js or JavaScript this link will help you a lot.

If you found this article is helpful, then please share this article's link to your friends to whom this is required, you can share this to your technical social media groups also. You can follow us on our social media page for more updates and latest article updates.
To read more about the technologies, Please subscribe us, You'll get the monthly newsletter having all the published article of the last month.