JavaScript: call(), bind() & apply() methods with examples

Table of contents

No heading

No headings in the article.

// Call method
let employeeOne = {
  fullName: 'John Doe', 
  age: 24, 
  salary: 40000, 
  salaryHike(hike) {
    this.salary += hike
  }
};
let employeeTwo = {
    fullName: 'Sarah Green', 
    age: 26, 
    salary: 60000
};

console.log("Call method"); 
console.log(employeeTwo.salary); 
employeeOne.salaryHike.call(employeeTwo, 10000); 
console.log(employeeTwo.salary);
console.log('---------------------------------------------------');

// Apply method
let employeeThree = {
  fullName: 'John Doe', 
  age: 24, 
  salary: 40000, 
  salaryHike(hike) {
    this.salary += hike
  }
};

let employeeFour = {
    fullName: 'Sarah Green', 
    age: 26, 
    salary: 60000
};

console.log("Apply method"); 
console.log(employeeFour.salary); 
employeeThree.salaryHike.apply(employeeFour, [10000]); 
console.log(employeeFour.salary);
console.log('---------------------------------------------------');

// Bind method
let employeeFive = {
  fullName: 'John Doe', 
  age: 24, 
  salary: 40000, 
  salaryHike(hike) {
    this.salary += hike
  }
};
let employeeSix = {
    fullName: 'Sarah Green', 
    age: 26, 
    salary: 60000
};

console.log("Bind method"); 
console.log(employeeFive.salary); 
const hikeEmployeeSix = employeeFive.salaryHike.bind(employeeSix, 10000); 
hikeEmployeeSix();
console.log(employeeSix.salary);
Output:
Call method
60000
70000
-------------------
Apply method
60000
70000
-------------------
Bind method
40000
70000

Execute above code here