DEV Community

hebaShakeel
hebaShakeel

Posted on • Updated on

Difference between call,apply and bind

In Object Oriented JavaScript, everything is an object and therefore we can set and access additional properties to functions and methods via the prototype

Call( ): The call() method invokes a function with a given 'this' value and arguments provided one by one. This means that we can call any function, and explicitly specify what 'this' should reference within the calling function.

Alt Text

Apply( ): Invokes the function and allows you to pass in arguments as an array.

Alt Text

Bind(): returns a new function, allowing you to pass in an array and any number of arguments.

Alt Text

When we use the bind() method:

1.The JS engine is creating a new invite instance and binding friend1 and friend2 as its 'this' variable. So basically it copies the invite function.

2.After creating a copy of the invite function it is able to call inviteFriend1( ) and inviteFriend2( ), although it wasn’t on the friend1 and friend2 object initially. It will now recognizes its properties and its methods.

Call and apply are pretty interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. Whereas Bind creates a new function that will have this set to the first parameter passed to bind().

Thank You!

Top comments (6)

Collapse
 
ciochetta profile image
Luis Felipe Ciochetta

So, I know how these functions work, but I can't quite figure out when they are useful

when would you want to use call(function, arg) instead of function(arg)?

Collapse
 
hebashakeel profile image
hebaShakeel

We use call, bind and apply methods to set the 'this' keyword independent of how the function is called. This is especially useful for the callbacks. Also, functions are a special kind of objects in JavaScript. So they have access to some methods and properties. Call, bind, and apply are some of the methods that every function inherits.

Collapse
 
ciochetta profile image
Luis Felipe Ciochetta

ah, got it

really hadn't thought about callbacks, but that makes some sense

Thread Thread
 
alifattah profile image
Ali Fattah • Edited

Sometimes the bind() method has to be used to prevent losing this, especially in callback. but actually, in ES6 we use the arrow function instead of bind hack to avoid such unwanted mistakes!✌

Collapse
 
prachi09051999 profile image
Prachi Tripathi

Really helpful article!!

Collapse
 
hebashakeel profile image
hebaShakeel

Thank you. I am glad it helped