JavaScript :[call(),apply(),bind()]

JavaScript :[call(),apply(),bind()]

Introduction

We were introduced to the this keyword. It took us a little while to get comfortable with the this keyword, but once we did we began to realize how useful it is. The value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called .this is used inside a function, and will always refer to a single object — the object that invokes (calls) the function where “this” is used. Here call ,apply and bind comes to the scenario . They are referred to as function borrowing methods . They help us reuse a function with different objects we call it .

call() ,apply(),bind()

const obj={
  name:"aman",
  printName:function (){
    console.log(this.name)
  }
}
obj.printName()

As we know of our knowledge of "this", this code prints "aman" on the console . Now lets see how does call() helps us .

call():

Let us look in the syntax

Function.call (thisArg, arg1, arg2,…..argn);

let us see the below code for implementation of call() method:

const obj={
  name:"aman",
  printName:function (greet){
    console.log(greet +" "+this.name)
  }
}
obj2={
  name:"obama"
}
obj.printName("hello")
obj.printName.call(obj2,"hello")

here the expected output is "hello aman" "hello obama"

so with call() method we reused the function printName() but the this refernce was passed with an other object (obj2) .

apply():

let us look in the syntax:

Function.apply(thisArg, argsArray)

let us see the below code for implementation of apply() method:

const obj={
  name:"aman",
  printName:function (greet){
    console.log(greet +" "+this.name)
  }
}
obj2={
  name:"obama"
}
obj.printName("hello")
obj.printName.apply(obj2,["hello"])

here the expected output is "hello aman" "hello obama"

The explanation is similar to call() method ,but the only difference is that we pass an argument array to apply() method.

bind():

let us see the syntax.

Function. bind(thisArg, arg1, ... , argN)

It returns a function to us unlike call and apply methods.

let us see the below code for implementation of bind() method:

const obj={
  name:"aman",
  printName:function (greet){
    console.log(greet +" "+this.name)
  }
}
obj2={
  name:"obama"
}
obj.printName("hello")
const printName2=obj.printName.bind(obj2,"hello")
printName2()

here the expected output is "hello aman" "hello obama"

Here we can see that unlike call and apply a function is returned which is envoked later ,this is major reason one may use bind method and for passing arguments we use comma separator .

Difference between call , apply , bind :

blog2-diff.png

Conclusion

Its the simplest explanation of the function borrowing methods . I hope after reading the blog one may be totally confident about the methods but practicing on own is the best process .

Thank You !! Happy Learning