Javascript: bind(), call() and apply()
js programmers must know this method
### bind()
The bind() method creates a new function, when called, has its this keyword set to the provided value.
const person = {
name: 'Tom',
salary: 15000,
houseRent: function (amount, vat, tax) {
return this.salary = this.salary - amount - vat - tax;
}
};const firstPerson = {
name: 'Piter',
salary: 20000
};const firstPersonHouseRent = person.houseRent.bind(firstPerson);
firstPersonHouseRent(2000, 100, 20);console.log(`${firstPerson.name} Balance : ${firstPerson.salary}`);
// Piter Balance : 17880
### call()
It can be used to invoke (call) a method with an owner object as an argument (parameter).
const person = {
name: 'Tom',
salary: 15000,
chargeBill: function (amount, vat, tax) {
return this.salary = this.salary - amount - vat - tax;
}
};const firstPerson = {
name: 'Piter',
salary: 20000
};person.chargeBill.call(firstPerson, 2000, 100, 20);console.log(`${firstPerson.name} Balance : ${firstPerson.salary}`);
// Piter Balance : 17880
### apply()
apply() method is used to call a function contains this value and an argument contains elements of an array.
const person = {
name: 'Tom',
salary: 15000,
chargeBill: function (amount, vat, tax) {
return this.salary = this.salary - amount - vat - tax;
}
};const firstPerson = {
name: 'Piter',
salary: 20000
};person.chargeBill.apply(firstPerson, [2000, 200, 20]);console.log(`${firstPerson.name} Balance : ${firstPerson.salary}`);
// Piter Balance : 17780
### Call vs Apply
The difference between call() and apply() is that call() passes all arguments after the first one on to the invoked function, while apply() takes an array as its second argument and passes the members of that array as arguments.
person.call(thisArg, 1, 2, 3) VS person.apply(thisArg, [1, 2, 3])
NB: Parameter separated by a comma for call() and Array for apply()