Class logic in javascript

Asked

Viewed 56 times

0

I will receive a JSON containing 2 objects: Player 1 and Player 2.

It would contain the following structure:

player 1:
playerid
socketid
name
points
jogada
player 2:
player 1:
playerid
socketid
name
points
jogada

I ended up creating this:

const player = require('../models/User');
const jogada = {
    pedra:{
        id:1
    },
    papel:{
        id:2
    },
    tesoura:{
        id:3
    }
}; 
const socketId = null

class Player {
    constructor({socket, name = "", jogada = "", points = ""}) {
        socketId = socket.socket.id
        this.id = player.id;
        this.name = player.name;
        this.points = player.points
        this.jogada = jogada;
    }

}

module.exports = Player;

In java it would be easier I would create a Players List and add these two players in it

But I was in doubt as I would do something like this in javascript?

Create 2 players with my json attributes that I will receive

1 answer

1


If I understand correctly, you can do so:

When you get the json, I think it will be "tree-grown" in something like this:

{
   //outros dados
   "players" : [
      "player1" : {
          //dados desse player
      },
      "player2" : {
          //dados desse player
      }
   ]
}

So take the json and traverses it with a loop of repetition ( a for of life ), like this:

for ( let player in json.players ) {
    let { socket, name, jogada, points } = players; // usei desestruturação
    let player = new Player({ socket: socket, name: name, jogada: jogada, points: points }); // instância  
    player.addList(); // add no array ( atributo de classe ) 
}

In your class, tidy the attributes to converge with the parameters, add a method to insert the instance into an array ( class attribute ) and make a class attribute, it would be something like that :

Class Player {
    constructor({socket, name = "", jogada = "", points = ""}) {
        this.socketId = socket.socket.id;
        //this.id = player.id; ** aonde vem o player.ID? o construtor não recebe esse parâmetro**
       //this.name = player.name; ** aonde vem o player? o construtor não recebe esse parâmetro**
       //this.points = player.points; ** aonde vem o player? o construtor não recebe esse parâmetro**
       // creio que o correto seria:
       this.name = name;
       this.jogada = jogada;
       this.points = points;
    } 
    addList() {
      Player.list.push( this );
    }
}
Player.list = new Array();

See this link to understand more about class attributes and instance attributes

I hope I helped 8), and of course, there are several other ways to make this logic, good luck with your lines of codes.

  • Thanks @Miqueias Moureira

Browser other questions tagged

You are not signed in. Login or sign up in order to post.