DEV Community

Excel Bill
Excel Bill

Posted on

Difference between call, bind and apply methods in javascript

Call(), bind() and apply() are javascript methods used to call a function with a specific this value and arguments where required. They are often used to set the context of a function and make it easier to reuse functions.

Asumming you have two objects, one contains a name and an annonymous function and the other only has a name like this;

let person1 = {
  name: "John",
  sayHi: function(hobby) {
    return "Hi, I'm " + this.name + " and I love " + hobby;
  }
};

let person2 = {
  name: "Frontend Jedi"
}
Enter fullscreen mode Exit fullscreen mode

but you'd to call the sayHi method for person2. This is where the call(), bind() and apply() methods come in, to do this, you simply set the this value of the method or function to point at the object it is referencing.

Here's how to go about it ;

Call() method

The call method recieves the new context i.e the new object, as the first argument followed by the function's arguments if any like so;

console.log( person1.sayHi.call(person2, "writing code") )
Enter fullscreen mode Exit fullscreen mode

apply() method

The apply method also recives the new context as the first argument but unlike the call method, the function's arguments are passed in as an array and seperated by comas if more than one. Like so;

console.log( person1.sayHi.apply(person2, ["writing code"]) )
Enter fullscreen mode Exit fullscreen mode

so if we had more than one hobby, our apply method would now look like this;

console.log( person1.sayHi.apply(person2, ["writing code", "designing"]) )
Enter fullscreen mode Exit fullscreen mode

bind() method

The bind method is a lot more different from the call and apply methods. To use the bind method, you need to first of all declare a variable and initialize it with the method or function you are referencing followed by the bind keyword and then the context object is then passed in as argument to the bind method. After initializing the variable like so;

let newSayHi = person1.sayHi.bind(person2)

the newly declared variable is then called as a function and the required arguments are then passed to it.

console.log( newSayHi("writing code")

In conclusion, bind(), call(), and apply() are important methods in JavaScript that allow us to control the value of the 'this' keyword and reuse functions more effectively. Understanding how to use these methods can greatly improve your ability to write more efficient and reusable code.

follow me on twitter @Frontend Jedi to stay updated. thanks.

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Hey, that was a nice read, you got my follow, keep writing 😉

Collapse
 
frontend_jedi profile image
Excel Bill

thank you so much, it means alot to me and I definitely won't stop.