Skip to content

Instantly share code, notes, and snippets.

@sunilmadaan07
Last active July 11, 2017 07:05
Show Gist options
  • Save sunilmadaan07/4116b258b8a53b6986532600aa261cce to your computer and use it in GitHub Desktop.
Save sunilmadaan07/4116b258b8a53b6986532600aa261cce to your computer and use it in GitHub Desktop.
bind, call and apply in javascript (brief description of bind, apply and call in javascript)
//@bind, apply, call in javascript
//@description
//@Question: If you want to use an arbitrary object as value of this, how will you do that?
/***********
Answer: There are at least three different ways to doing this by using bind, call and apply.
For example, I have a method named deductMontlyFee in the object monika
and by default value of this would be monika inside the method.
************/
/***********
If I bind the deductMontlyFee of monika with another object vikas
and pass vikas as first parameter of the bind function, vikas would be the value of this.
***********/
/***********
bind allows you to borrow a method and set the value of this without calling the function.
It simply returns an exact copy of the function with new value of this.
You can reuse the same function with new value of this without harming the old one.
***********/
//apply call the function immediately and allows you to pass in arguments as an array.
//call call the function immediately and allows you to pass in arguments one by one.
var monika = {
name: 'Monika Geller',
total: 400,
deductMontlyFee: function(fee) {
this.total = this.total - fee;
console.log(this.name + ' remaining balance is '+ this.total);
}
}
var vikas = {
name: 'vikas',
total: 500
}
var sunil = {
name: 'sunil',
total: 600
}
var mohan = {
name: 'mohan',
total: 700
}
//using bind
var deductVikasFee = monika.deductMontlyFee.bind(vikas, 200);
deductVikasFee(); // vikas remaining balance is 300
//using call
monika.deductMontlyFee.call(sunil, 200); // sunil remaining balance is 400
//using apply
monika.deductMontlyFee.apply(mohan, [200]); // mohan remaining balance is 500
@singhmohancs
Copy link

Good explanation.

@sunilmadaan07
Copy link
Author

Thanks!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment