A Newb's Pen

Let's learn together

JavaScript - Call vs Apply vs Bind



If you have landed on this page, You are most probably looking for when and how to use call, apply and bind. but we have got one prerequisite ‘know-how of this object’ to understand those js methods. So before we proceed. Lets get a refresher for ‘this’.

‘this’ Refresher

‘this’ is a fundamental element in object oriented programming.

Take out your mobile and say, “Hey Siri (or Hey Google), How old am i ?” The voice assistant will tell you your age. Millions of people ask same question to same assistant on their phone and all get different answers. Ever wondered, How ?

Simple. Your phone has a context. When ever you ask something to siri, she knows ‘I’ here is you i.e. phone owner. This context in object oriented programming is called ‘this’.

let’s check out the same with piece of code :

See the Pen JSBasics : this by Manish Kumar Khedawat (@mkkhedawat) on CodePen.


‘bind’ method

We saw same function giving different age depending on the context. Now what if I want to use a fixed context for particular function. Bind comes handy in there. According to MDN,

The bind() method creates a new function that, when called, has its ‘ keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Simple words, I can tell a function, Hey dude, if I bind you with ‘X’, you forget your ‘this’, and use my provided value ie. ‘X’ as ‘this’.

let’s check out the same with piece of code :

See the Pen JSBasics : bind by Manish Kumar Khedawat (@mkkhedawat) on CodePen.


You may ask : Is that’s all ? Well No ! You can use bind method to pass fixed arguments as well. Lets check out :

See the Pen JSBasics : bind - II by Manish Kumar Khedawat (@mkkhedawat) on CodePen.


Once you attach a bind, it can’t be changed. Chaining binds will take first bind and ignore rest. This makes sure that no other piece of code changes your expected this.

See the Pen JSBasics : bind - III by Manish Kumar Khedawat (@mkkhedawat) on CodePen.


‘call’ method

‘call’ and ‘bind’ both attach ‘this’ and argument into function. ‘bind’ returns function but call invoke the function immediately.

Let’s check out the syntax :

See the Pen JSBasics : call by Manish Kumar Khedawat (@mkkhedawat) on CodePen.


‘apply’ method

‘apply’ and ‘call’ acts the same way, only difference being ‘call’ takes functional arguments separated by comma but ‘apply’ takes functional arguments as an array object.

Let’s check out all three in action :

See the Pen JSBasics : call vs bind vs apply by Manish Kumar Khedawat (@mkkhedawat) on CodePen.


summary

All three method attach ‘this’ into a function. Use ‘bind’ when you want that function to be called later with a certain context, useful in events ( for ex. button click , setTimeout ). Use ‘call’ or ‘apply’ when you want to invoke the function immediately, and modify the context.




Comments