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 trialJamie Moore
3,997 PointsWhy does 'token.push' not require the 'this' keyword?
Following along with this video, and the majority of it makes sense, but one thing i'm struggling with, is why does the 'token.push' in the createTokens method not require 'this'?
The code in question:
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);
}
/**
* Creates token objects for player
* @param {integer} num - Number of token objects to be created
* @return {array} tokens - an array of new token objects
*/
createTokens(num){
for (let i = 0; i < num; i++) {
let token = new Token(i,this);
tokens.push(token);
}
return tokens;
}
}
1 Answer
denisegagne
24,704 PointsThis is because tokens is limited to the scope of the function. The createTokens() function should really include a secondary "let" variable like below, but the browser will sometimes recognize the intention and create the variable for you. Especially if "tokens" is the ID of another element on a page.
this.tokens doesn't "exist" until after the function is returned.
createTokens(num){
let tokens = [];
for (let i = 0; i < num; i++) {
let token = new Token(i,this);
tokens.push(token);
}
return tokens;
}
Jamie Moore
3,997 PointsJamie Moore
3,997 PointsThanks, that makes perfect sense. I'd completely overlooked the tokens array being created within the function.