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 Understanding "this" in JavaScript

Sheila Babadi
Sheila Babadi
5,241 Points

this.name and this.state

I don't quite understand why it's necessary and/or better to use this.name and this.state in the function printMyCityAndState (or whatever it was called). If it were just "name" and "state", wouldn't the correct values still be printed if you were calling it on a specific instance of that object?

P.S. You forgot the Portland Thorns!!!

1 Answer

Steven Parker
Steven Parker
231,261 Points

Remember that the method is being defined inside the constructor for City.

Inside the constructor, the names "city" and "state" refer to the arguments passed to the constructor, not to the instance variables they get assigned to. So to make sure the method uses the instance variables, the variable names must be prefixed with "this.". Also, the contents might be different if the arguments were undefined when the constructor was called.