OneCompiler

Call, Apply and Bind methods in Javascript

365

In Javascript function call, apply and bind is doing exactly the same. But there is a lot of confusion when to use it and how it works. In this post, I am going to explain what is the difference between call, apply and bind.

In every OOP concept, every object have its own properties and methods. In javascript, we can also achieve two objects can call the same method using call, apply and bind methods.

** Call():**

Call method is used to call a function with an object and functional arguments.

let's see an example

let obj = {name: "Madhav"}

var fullName = function(lastName) {
  return this.name + " " + lastName
}

console.log(fullName.call(obj, "Krishna"));

//output: Madhav Krishna

In the above example, there is a function called fullName with an argument called lastName and it returns fullName by adding obj.name and lastName.

The method fullName can access the object obj by using call() method. So we can call a function with an object using the call method.

If we need to pass multiple arguments to a function we can do like this.


let obj = {name: "Madhav"}

var fullName = function(lastName, middleName) {
  return this.name + " " + middleName + " " + lastName
}

console.log(fullName.call(obj, "Thatavarthi", "Krishna"));

//output: Madhav Krishna Thatavarthi

So we can simply attach multiple arguments individually using the call() method.

** Apply: **

Both Apply and Call methods are similar. The only difference between these is we need to pass every argument individually in the call() method. Whereas apply() method expects an array of parameters.


let obj = {name: "Madhav"}

var fullName = function(lastName, middleName) {
  return this.name + " " + middleName + " " + lastName
}

console.log(fullName.call(obj, ["Thatavarthi", "Krishna"]));

//output: Madhav Krishna Thatavarthi

Bind method:

bind() method is used to bind the function to an object. In this, whatever we passed as a first argument will determine as the value of this.

So if pass person object as an argument to the walk function then this will point towards person object no matter how we call the function.


const person = {
 name:"madhav", 
 age: 16,
 walk() {
  console.log(this);
 } 
}

person.walk(); // It prints {name:"Madhav", age: 16, walk: f}

const walk = person.walk.bind(person);
walk();  // It prints {name:"Madhav", age: 16, walk: f}

So in the above example, we are binding walk method to the person object. That's why we got the person object as output instead of undefined.