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

James Croxford
James Croxford
11,397 Points

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) { = 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));
        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"?