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 Object-Oriented JavaScript Getters and Setters Setters

Andrew Lim
Andrew Lim
8,004 Points

Why would you not put the _owner in the constructor?

Why would you not put the _owner in the constructor?

If you have access to the class, wouldn't it be easier to read if all your properties are set there?

I'm still having trouble with the concept with tutorials the reason why information is added after the fact, using expressions to create properties that don't exist yet. Is it just for demonstration purposes, is it because normally people don't have access to change the class and have to use this method, or is it common practice and just something I should get used to?

2 Answers

Steven Parker
Steven Parker
231,275 Points

I think the "owner" is a reasonably good practical example of data added after an instance is created. In this case, the pet instance might be created to keep track of a pet that is is available for adoption. Then some time later, the pet may acquire an owner (when the owner adopts the pet).

That info could not be part of the constructor because the value is not known at the time of instance creation.

I think the main reason is that, you are using setters to restrict the setting of that particular property. For example, if you create a setter for the breed, then you would like to restrict values to valid breeds only.