DEV Community

Cover image for Distinguish between Bind, Call and Apply methods in Javascript.
Faisal Ahmed
Faisal Ahmed

Posted on • Updated on

Distinguish between Bind, Call and Apply methods in Javascript.

Bind: If you want to use another object's property in an object method, you can bind it.
Just call the method and bind it to that object.
More important thing in the bind method is, the bind method returns a function. So you need to call the function again.
You can also pass more parameters, inside the bind method.

For example:

let person = {

    fullName: function(city,country) {
        console.log(this.firstName + ' ' +this.lastName +' staying '+ city + ' ' +country);
    }
};

let person1 = {
    firstName: 'Faisal',
    lastName: 'Ahmed'

};

let person2 = {
    firstName: 'I am',
    lastName: 'FAS'

};

let binded = person.fullName.bind(person1,"Dhaka","Bangladesh");
binded();

Enter fullscreen mode Exit fullscreen mode

output: Faisal Ahmed staying Dhaka Bangladesh


Call: The call method is similar to the bind method. But the difference is that the call method does not return a function like bind method. It directly shows the output.
More important thing in the call method is, the call method passes more parameters, inside the call method. But parameters are separated by comma, comma.

For example:

const person = {

    fullName: function(city,country) {
        return this.firstName+ " " +this.lastName + " staying "  +city+  " in "  +country;
    }
};

const person1 = {
  firstName: "Faisal",
  lastName: "Ahmed"
}

const person2 = {
  firstName: "I am",
  lastName: "FAS"
}


console.log(person.fullName.call(person1,"Dhaka","Bangladesh"));

Enter fullscreen mode Exit fullscreen mode

output: Faisal Ahmed staying Dhaka in Bangladesh


Apply: The apply method is similar to the call method. The apply method also does not return a function like bind method. It directly shows the output.
More important thing in the apply method is, the apply method passes more parameters, inside the apply method. But parameters will be an array.

For example:

const person = {

    fullName: function(city,country) {
        return this.firstName+ " " +this.lastName + " staying "  +city+  " in "  +country;
    }
};

const person1 = {
  firstName: "Faisal",
  lastName: "Ahmed"
}

const person2 = {
  firstName: "I am",
  lastName: "FAS"
}


console.log(person.fullName.apply(person1,["Dhaka","Bangladesh"]));

Enter fullscreen mode Exit fullscreen mode

output: Faisal Ahmed staying Dhaka in Bangladesh


Top comments (0)