DEV Community

Cover image for Javascript- call(), apply(), bind()
Shuvro_baset
Shuvro_baset

Posted on

Javascript- call(), apply(), bind()

This:
In javascript one of the most important and confusing topics is ‘this’. It's a reserved keyword, we do not use it as variable or function name.
This means that “this” can only be used in a function, or globally. When used in either of these cases, “this” refers to the window object. When the function is a method of an object, then “this” refers to the object that the method is a member of. When the function is a constructor, then “this” refers to the instance object. There is much more to talk about with regards to what “this” means in varying scenarios, but these are the most common situations.

Call, Bind, Apply:
We use call, bind and apply methods to set ‘this’ keyword independent of how the function is called. This is especially useful for the callbacks.

These Three methods take the value of this or centext of this as a first argument. But call() and bind() can take unlimited arguments. On the other hand apply() can take only two arguments. First one is the value or context and the second one is an array.

In which function we use call() and apply() method that function will be called instant. On the other hand, the bind() method did not call it instant, it returned a function definition so that we can call it later as we want.

Examples:
const normalPerson = {
firstName: 'shuvro',
lastName: 'baset',
salary: 15000,
getFullName: function() {
console.log(this.firstName, this.lastName);
},
chargeBill: function(amount, tips, tax) {
console.log(this)
this.salary = this.salary - amount -tips - tax;
return this.salary;
}
}

normalPerson.chargeBill(100);
console.log(normalPerson.salary)

const zeroPerson = {
firstName: 'zero',
lastName: 'person',
salary: 5000,
}

const heroPerson = {
firstName: 'hero',
lastName: 'person',
salary: 25000,
}

// i will bind chargeBill function to heroPerson
const heroChargeBill = normalPerson.chargeBill.bind(heroPerson);
heroChargeBill(2000);
heroChargeBill(1000);
console.log(heroPerson.salary)
console.log(normalPerson.salary)

// call function
normalPerson.chargeBill.call(heroPerson, 900,100,10);
console.log(heroPerson.salary)
normalPerson.chargeBill.call(zeroPerson, 2000, 200, 20);
console.log(zeroPerson.salary)

// apply
normalPerson.chargeBill.apply(heroPerson, [1000, 200, 20]);
console.log(heroPerson.salary);
normalPerson.chargeBill.apply(zeroPerson, [500, 501, 501]);
console.log(zeroPerson.salary);

Top comments (0)