Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Mark Tripney
Mark Tripney
8,666 Points

Would this be a valid use for a getter?

I’m trying to understand the design of OOP code as much as the syntax. And, it’s tough! As a practice exercise, I’m building a little program to generate characters for a role-playing game...

I’d like to have a Character class. When objects are instantiated from this class, I’d like to have the object’s initial quantity of silver randomised, according to a formula (so, they could start with anything from 20 to 120 pieces of silver - two d6 x 10, RPG fans!)

Now, would this be a suitable getter? MDN defines get as, “ The get syntax binds an object property to a function that will be called when that property is looked up.” This sounds like what I’m after, I think... ? Or would a straightforward method be better, attached as a value to the property in the constructor?

Thoughts/corrections to my understanding welcome!

2 Answers

You wouldn't want their silver to be randomized every time you get the value, so you'd randomize it during construction.

The getter would simply look up the current value

Mark Tripney
Mark Tripney
8,666 Points

Thanks, Zimri. Perhaps I'm misunderstanding the purpose of a getter. I'd only want the value to be randomised once, at the point of instantiation... so there would never really be a need to look up the value, as I understand it. Once the objects — the actual characters — have been created, their property values (in this example, how much silver they have) would be handled per object, and not via the class?

So, would a getter be used to look up a value which existed outside the class, but which was important to the class when it's called?