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 Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects createTokens() Method Solution

I don't know what "this" is referred to in let tokens = new Token(i, this);

Thanks for help

2 Answers

Schaffer Robichaux
Schaffer Robichaux
21,728 Points

Arshia,

That's a great question. I have always had trouble determining the lexical scope of "this". In this instance, "this" is being called with a "new" constructor method (basically hijacking a regular function with the "new" invocation). In this instance, "this" becomes part of the newly constructed object.
One of the best resources I have found for this topic is Kyle Simpson's "You don't know JS: this & Object Prototypes". He has been kind enough to put it on GitHub- the link to the chapter relating to your question is below: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md

...my copy is heavily bookmarked and highlighted :)

Chris Shaffer
Chris Shaffer
12,029 Points

An easy way to think of "this" might be that inside a plain old object, "this" refers to the object itself; you could think of "this" as the object's identity.

In other words, for the object "this" = "me, this object", which means everything from the opening to the closing bracket when that object is declared.

It might help to think of "this" as what it does NOT refer to. Inside the object you might have a value of someProperty, but you might also have that value somewhere else; when you say "this", you're kind of explicitly saying, "this, right here - this VERY someProperty that belongs to this object - an no other".