DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

Reusing object properties with call() method in JavaScript

Suppose we have an object with properties that we want to re-use for a certain new object.

JavaScript provides a call method that we can use to achieve this objective.

//Sample object
var emp = {
   salary_per_day: 10,
   monthlySalary: function(){
   return this.salary_per_day * 30;
   }
};

//call the function 
emp.monthlySalary();
> 300

Enter fullscreen mode Exit fullscreen mode

We can use the call method here on the new object to use the method of the existing object.

var emp = {
   salary_per_day: 10,
   monthlySalary: function(){
   return this.salary_per_day * 30;
   }
};


var emp2 = {salary_per_day: 50};

emp.monthlySalary.call(emp2);
> 1500

Enter fullscreen mode Exit fullscreen mode

Like this. call function can be utilized to reuse the property of another function.

Top comments (0)