How bind differs from call and apply in Javascript

When it comes to changing the context of a function execution, as mentioned in the post here, Javascript offers one more function ‘bind’ other then ‘call’ and ‘apply’.

As shared in other post, the way we can pass the reference of current ‘this’ object using call and apply, similarly, using ‘bind’ too we can pass the current ‘this’ object to the function and make the function execute as per the context of object passed by us.

The main difference between bind and call/apply lies in the fact that call/apply make the function execute instantly, where as, bind in a way creates a new function with new context that is called later on as required, like in case of event firing or callbacks etc..

Thus, if we want to associating a different context for a function and instead of invoking it instantly we want to invoke it at a callback then using bind is the way to go for.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s