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

Hard time understanding code

/**
 * 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 having hard time understanding code. Why we wrote and what does it do. If anyone can explain it is much appreciated.

Also, we passed 21 in the constructor. Then why do we require to write this method? Cant we split the tokens between players?

Félix Guérin Camilo Lucero

2 Answers

Akshay Alok
Akshay Alok
7,857 Points

This method is a behavior defined for the class "Player" in Player.js. What this does is that it creates an array with a number of "Token" objects for the player to play. When this method is called in the constructor it can be seen analogous to "giving the player" a set number of tokens (21 in this case).

So we can say that this method is used for making an array of Token objects and returning it to be assigned to the tokens property of a player. Calling it in the constructor just means that, by default players will get a token array with (21) tokens in it.

Steven Parker
Steven Parker
221,324 Points

The number passed to the constructor is not related to the players. It's just a count of how many tokens you want the function to create.

Okay. Can you also help me understand the above code?

Steven Parker
Steven Parker
221,324 Points

I"m not sure what part you may find confusing. I'll try to answer any specific questions you have about it.