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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay