What is the difference between call apply and bind in javascript?

 Call, apply, and bind in javascript?


We can start to know about javascript default methods like call, apply and bind. These methods are the defaults method of the javascript, we can understand with an example as below:

 

function animal (name, eat, voice) {

            this.name = name;

            this.eat = eat;

            this.voice = voice;

        }

        const aniDetails = function (){

                console.log(`${this.name} ${this.eat}, ${this.voice}`)

            }

 

        let Animal = new animal('Cat', 'Rat','Meow');

        aniDetails.call(Animal);

 

 // Cat Rat, Meow

 

We have created a constructor function and then call it as the above example.

Always point this object to global object and here is a global object is window objects.

If we need to access object value then we require to call function because call method needs this object as a parameter.


So we need to call function as below example:

aniDetails.call(Animal);

 

If we need to pass any argument in the function so we can pass as color…

const aniDetails = function (color, nickname){

                console.log(`${this.name} ${this.eat}, ${this.voice}, color: ${color} - ${nickname}`)

            }

 

        let Animal = new animal('Cat', 'Rat','Meow');

        aniDetails.call(Animal, 'Black', 'Pussy');

        //Cat Rat, Meow, color: Black - Pussy

 

“Call methods need to comma separated value as argument.”


let AnimalNew = new animal('Lion', 'Meat','Roar');

        aniDetails.apply(AnimalNew, ['Red', 'Singha']);

        //Lion Meat, Roar, color: Red – Singha

 

The above code shows that we pass the same value in apply method with an array, a first argument is an object and the second is an array.


So call and apply method are similar only difference comma-separated and array.


“Bind method always gives a new function with set this.”

let newAniFunc = aniDetails.bind(Animal);

 newAniFunc('Black', 'Pussy');

 //Cat Rat, Meow, color: Black – Pussy

 

As the above example indicate to bind method functionality when we create a function with bind method. It gives us a new bounded function to set this object, we need to only pass comma-separated values.


The above methods give a lot of benefits as we have created a one-time constructor function and created a one-time method and call again and again. Only need to create a new object.


 

No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.