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 trialJannick Moth
8,714 PointsHow is owner.id working?
I'm not sure how owner.id is declaring itself. I tested the code and I see that it creates a unique value but I can't work out how it gets there
class Token {
constructor(index, owner){
this.owner = owner;
this.id = token-${index}-${owner.id}
;
this.dropped = false;
}
}
class Player { constructor(name, id, color, active = false) { this.name = name; this.id = id; this.color = color; this.active = active; this.tokens = this.createTokens(21); }
createTokens(num) {
var array = [];
for(var i = 0; i < num; i ++) {
var newCounter = new Token(i, this);
array.push(newCounter);
}
return array;
}
}
Any explanations?
Thanks in advance.
2 Answers
Steven Parker
231,172 PointsWe can see from this code that any object of class "Player" is passed an id (along with a name and color) when it is constructed. Then, when an item of type "Token" is created, an index number and a reference to a "Player" object is passed in.
The unique ID established in a "Token" object comes from this assigment:
this.id = `token-${index}-${owner.id}`;
That's a template string. Each identifier along with the braces and leading dollar sign will be replaced by the string representation of the value that the identifier contains. This process is called interpolation.
For example, if the variable "index" contains 3, and the "owner" has an "id" set to "joe", then `token-${index}-${owner.id}
` would be interpolated into the string "token-3-joe".
Jannick Moth
8,714 PointsHi Steven, thanks for the reply
I think I understand the template literal part, but I'm still confused as to when owner.id is declared. As I understand it, it's only mentioned once (in the template literal) - and owner is never declared as an object, only as the property of an object.
How does the player.id property find it's way to the owner.id property? Can a property have properties of it's own? is "id" a variable that is passed in and then any time it's mentioned in the objects it is called to that value?
Thanks again, Jannick
Steven Parker
231,172 PointsSteven Parker
231,172 PointsIn answer to your additional questions: Yes, if a property is also an object it can certainly have properties of its own.
A more granular breakdown of the "owner.id" reference:
If it's still not clear it might help to look at some of the code where these definitions are actually used.