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 trial

JavaScript Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects createTokens() Method Solution

Clarification on the use of the 'this' keyword inside of createTokens()?

Just for reference, here's the code from Player.js

class Player { 
    constructor (name, playerID, tokenColour, isTurn = false) {
        this.name = name;
        this.playerID = playerID;
        this.tokenColour = tokenColour;
        this.isTurn = isTurn;
        this.tokens = this.createTokens(21);
        /* Set the token property to the return value from the method call
           When calling the create tokens method, using the 'this' keyword- this.createTokens(21);
           Indicates that the method I want to call is available on the object that we're initialising
        */
    }

    /**
     * Creates token objects for player
     * @param     {integer}    num - Number of token objects to be created
     * @returns   {Array}     tokens - An array of the newly created token objects
     */
    createTokens(num) {
        const tokens = [];
        for (i = 0; i < num.length; i++) {
            let token = new Token(i, this);
            //token variable could be refactored out to tokens.push(new Token(i, this));
            tokens.push(token);
        }
        return tokens;
    }
}

Within the createTokensMethod, we have:

let token = new Token(i, this);

Attempting this segment by myself, I had instead wrote:

let token = new Token(i, Player);

Am I right in thinking the following: "What I wrote was incorrect, because I was passing the Token class and its constructor the CLASS of Player, and not the particular INSTANCE we are in of that Player class. By passing the Token class 'this' as an argument (i.e. following what the instructor wrote), we are now instead passing this instance of the Player class to instantiate the Token class"?

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

Am I right in thinking the following: "What I wrote was incorrect, because I was passing the Token class and its constructor the CLASS of Player, and not the particular INSTANCE we are in of that Player class. By passing the Token class 'this' as an argument (i.e. following what the instructor wrote), we are now instead passing this instance of the Player class to instantiate the Token class"?

Sounds right to me!