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: Challenge Adding the Game Logic get owner() Solution

is the get owner() made only to save ourselves one step?

Writing this getter method in the Space class seems to me kind of unnecessary. Wouldn't we get the same effect writing: targetSpace.token.owner (and not just "targetSpace.owner()" )? Do you guys know what'd be the main difference between those two?

1 Answer

Hi Carlos, first of all, the targetSpace variable is scoped to the playToken() method. Hence you cannot access it outside the method. Also targetSpace is either null or of the object type Space. Space does not have a property named owner. Token does however.

The getter method contains logic checking whether or not the space has a token in it. If it does not, we can't retrieve any owner, which the logic accounts for. Otherwise you'd have to write this logic every time, before you could retrieve the owner.

This way of segmenting the code into chunks, is the very point of object oriented programming. Objects model a given data type and also the behavior and functionality belonging to it. We want to retrieve the owner of the token in a given space. In other words we want to run the get owner method on an instance of the Space class.

Hope that makes sense.

https://en.wikipedia.org/wiki/Object-oriented_programming

Yeeeah.. you're right! I didn't think of it like that. I got confused because I ignored the fact that 'targetSpace.token.owner' cannot give me the owner of the token if token = null. So "targetSpace.owner()" would already have checked that there was a token in the first place. Thank you, Marcus, for the clarification!