DEV Community

AR Addula
AR Addula

Posted on • Updated on

JS Polyfills - Call, Apply, Bind

If you are here, I guess you would either be looking for new opportunities or honing your skills. I would like to help for either reasons with this article. Let's directly jump in to the topic without wasting our read time 🤘

Polyfill for Call

Explanation:

What exactly is this 🧐 -> arguments[0].fn = this;

In this above statement this refers to calling function i.e; displayUser

  • We are creating a property(fn) on object and assigning displayUser function to it
  • Above would create an additional property fn on the passed object(user)
  • Now, fn would have access to this on user object as fn is user objects property now
  • So, pass only parameters now to function fn now, as it takes care of this
  • Both runCall and runCall2 are valid polyfills for call where runCall2 has defined parameters and runCall depends on arguments object
  • Look at the code below and compare with lines written inside function runCall

Polyfill for Apply

Apply polyfill is similar to call except that apply takes arguments as Array along with object(context)

Polyfill for Bind

Here comes the solution for our wait, atleast I feel though 😉

There are two functions created for bind polyfill in the above code. One is using [].slice.call(arguments) and the other one is using rest/spread syntax ...arguments

Thank you for taking time to read my article. I know there would always be something to improve. Please feel free to share your thoughts 👐

Top comments (2)

Collapse
 
ivasilichi profile image
Oleg Vaskevich

arguments[0].fn(...[].slice.call(arguments,1)); You implementing call polyfill using call, how is that even polyfill?

Collapse
 
araddula profile image
AR Addula

@ivasilichi Thanks for pointing this out. I was more concentrating on "bind" polyfill and overlooked "call". I was also not active on this forum so far. It is corrected/updated now. Thanks again