Apply vs Call vs Bind Examples
The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.
- Call invokes the function and allows you to pass in arguments one by one.
- Apply invokes the function and allows you to pass in arguments as an array.
- Bind returns a new function, allowing you to pass in a this array and any number of arguments.
Call
Call invokes the function and allows you to pass in arguments one by one.
Apply
Apply invokes the function and allows you to pass in arguments as an array.
Bind
Bind returns a new function, allowing you to pass in a this array and any number of arguments.
When To Use Each
Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.
I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array.
Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.
Bind is great for a lot of things. We can use it to curry functions like in the above example. We can take a simple hello function and turn it into a helloJon
or helloKelly
. We can also use it for events like onClick
where we don’t know when they’ll be fired but we know what context we want them to have.
Reference: codeplanet.io