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!

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 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,729 Points


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,030 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".