When Should Use Getter Method and When Should Use Common Method?

In task 4 of the Meal Maker project, I need to creat getter method for the property inside an object in order to return the value of the property.

But I can also achieve this goal with common method:

returnValue() {
    return this.property;
}

besides the getter method:

get property() {
    return this.property;
}

It looks like it’s better to use getter method instead of common method in this case, but why?

I’ve found two clues:

  • In this post of codecademy forum, it says it’s a programming paradigm.
  • And in this post of quora, it says the getter method is a discription of a property and the common method is the manipulation of a property.

But I still can’t totally undersant the reason.

1 Like

How do we normally declare and retrieve an object property?

obj = {}
obj.prop = 'value'
console.log(obj.prop)    //  value

We’re polling the object property directly. There is no vector for manipulation, evaluation, formatting, &c. It’s a direct access poll.

Getters let us change all that.

2 Likes

My earlier reference to it being part of a paradigm was in reflection that since Javascript can’t phase out features (since it will create backwards compatibility issues), it tends to have a lot of ways to do one thing, including how to write a class legally. The paradigm of object oriented programming has a model way to construct a class (getters, setters, public and private data members, etc) which you should look more into if it’s something that interests you.

Reference for getters: getter - JavaScript | MDN

2 Likes

Literal definition of objects is pretty much confined to close spaces (inner context or scope). Global objects tend to belong to a class of objects. This gives us greater mobility and usability. Once we define a class of objects, we ingrain a fingerprint on all the objects we spawn from that class.

1 Like

Thanks for your answer~

Through your answer, I understand that I can manipulate the value with get method when accessing the property which can’t be achieved by directly accessing the property.

Thanks a lot and wish you have a nice day :grinning:

1 Like

So the getter method and common method are the different ways to achieve the same goal. But the former is the paradigm in the new standard and the latter exists just for compatibility. And it’s better to choose the model way to format our codes.

Well, it really becomes much clearer after reading your answer~

Wish you have a nice day :smiley_cat: