简体   繁体   中英

How does the keyword “this” work in this example?

So in the below code, I was wondering how the this keyword works here? Also where does the i and this go to from the createstoken function?

Does it go to the this.id in the token class? If so why?

class Player{
    constructor(playerNumber, tokenCount, tokenColor, active = false){
        this.playerNumber = playerNumber
        this.tokenCount = tokenCount
        this.tokenColor = tokenColor
        this.active = active
        this.tokens = [createTokens(21)]
    }
    //creates tokens
    createTokens(num){
        let array = []
        for(let i=0; i<num; i+=1){
            const token = new Token(i, this)
            array.push(token)
        }
        return array = []
    }
}//end player

class Token{
    constructor(){
        this.owner = owner;
        this.id = `token-${index}-${owner.id}`;
        this.dropped = false;
    }

}//end token

Thank you for the help!

In your code, this refers to the new object that is being constructed when the instance of the class is created:

class Player {
    constructor(playerNumber) {
        this.playerNumber = playerNumber;
        //This refers to whatever object is being created - in the below instance, `this` would refer to `newPlayer`
    }
}

const newPlayer = new Player(25);

Current object which is invoked will be taken as this.checkout the simple example as i have used "this" variable to construct a object.

"new" keyword can be used in constructor function to refer a unique object.

checkout the example:

 function Maker(name,age){ //current object will be taken as this. this.name=name; this.age=age; return this; } let firstObject = new Maker('bathri',22); let secondObject = new Maker('bathri',22); let result = [firstObject,secondObject]; console.log("first object",firstObject); console.log("second object",secondObject); console.log("result",result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM