DEV Community

Cover image for JavaScript - Object methods
Zouhair Sahtout
Zouhair Sahtout

Posted on

JavaScript - Object methods

We already said that a "function" is just a value, so we can add function to object as a value

Image description

We should avoid passing something manually if we already have it.
In this example we already have the birth year in our object
So to access the birth year property from the object we use **this** keyword.
Which is equal to the object that we calling it from.

Example:
Image description


The power of this keyword
Image description

Let's say that we need to access the age in our object multiple times throughout our program.
So that would be calling the zouhair.calcAge() multiple times.

In this computation here: 
return new Date().getFullYear() - this.birthYear;

it's not big deal, but what if it was a bit heavier, that’s a problem.

Instead when calculate the age once, then store it in the object.


Finally:

Having the exact same code in both of these objects we fall into DRY

Solution:

there's a better way which can avoid this  called: Object-Oriented-Programming

Top comments (0)