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 trialBilly Jones
28,560 PointsI am not sure what this does in this instance let token = new Token(i, this);
-
Creates token objects for player
- @param {integer} num - Number of token objects to be created
- @return {array} tokens - an arary of new token objects */ createTokens(num) { const tokens = [];
for (let i = 0; i < num; i++) { let token = new Token(i, this); tokens.push(token); }
return tokens; }
I am not sure what this references in this instance. Can someone help me out
1 Answer
Josef Janousek
13,777 PointsHello Billy Jones basically you are creating a new instance of class Token by new keyword as you might know. you can see in the Token constructor function you have two arguments (index,owner) and the Player js inside of createToken method you are initiating the class Token by passing this two value from the for loop (i,this) here (I = jndex) & this refer to the owner. Below I have created a simple example for you you can just copy and paste those to the developer console so you can see .
class Token {
constructor(index, owner) {
this.owner = owner;
this.id = token-${index} - ${owner.id}
;
}
}
undefined
class Player {
constructor() {
this.name = "sayeed";
this.tokens = this.createTokens(4);
}
createTokens(num) {
const tokens = [];
for (let i = 0; i < num; i++) {
let token = new Token(i, this);
tokens.push(token);
}
return tokens;
}
}
const p = new Player(); console.log(p);