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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay