Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,083 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.