Javascript: method as object builder?

Asked

Viewed 37 times

1

I would like to create a method within an object, but it assigns the properties to the object itself:

Game = { personagens: [] };
Game.Personagem = function(obj = {}){
    
    this.nome     = obj.nome    || "desconhecido";
    this.hp       = obj.hp      || 3;
    this.ataque   = obj.ataque  || 1;
    
    Game.personagens.push(this);
}

Game it was like that:

Game 
    {personagens: Array(0), Personagem: ƒ}
/* ok */    Personagem: ƒ (obj = {})
/* ok */    personagens: []
        __proto__: Object

But when it executes new Game.Personagem() or just Game.Personagem(), those attributes go to the object Game:

Game 
    {personagens: Array(0), nome: "desconhecido", hp: 3, ataque: 1, Personagem: ƒ}
/* ok */    Personagem: ƒ (obj = {})
/* ok */    personagens: []
/* ?? */    ataque: 1
/* ?? */    hp: 3
/* ?? */    nome: "desconhecido"
        __proto__: Object

So it is not possible to create constructors inside objects?

  • 1

    In the scope of the function you declared, the variable this contains the Game object itself, so when you do this.nome = "fulano", you are creating an attribute nome in your Game object, or changing if the attribute already exists.

  • Yes I noticed. But I would like to create a constructor within the Game object. Maybe this question was more direct, but I wanted to be softer so maybe my doubt would be for someone since I did not find similar.

  • 1

    The constructor would work if you were using the operator new. The estate personagens and method Personagem are like "static methods"...

  • But it’s written there (new Game.Personagem() or Game.Personagem()). And it works anyway. The point is that it assigns properties to the object, which wouldn’t happen if it were an isolated constructor function. And the solution I could give would be to create an artificial constructor, if I may call it that, by putting an auxiliary variable (aux.ataque = controle.ataque || "KeyA") and in the end give return aux. But it doesn’t suit me because he would be creating a copy and not a reference in Game.personagens.push(aux)

  • But that’s correct... the values are being entered in the characters array, which belongs to the Game. Game{ Character: Function Character(obj). characters: (2) [ 0: Object { name: "unknown", hp: 3, attack: 1 } 1: Object { name: "test", hp: 3, attack: 1 } ] }

No answers

Browser other questions tagged

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