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?
In the scope of the function you declared, the variable
this
contains the Game object itself, so when you dothis.nome = "fulano"
, you are creating an attributenome
in your Game object, or changing if the attribute already exists.– G. Bittencourt
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.
– Zano
The constructor would work if you were using the operator
new
. The estatepersonagens
and methodPersonagem
are like "static methods"...– Luiz Felipe
But it’s written there (
new Game.Personagem()
orGame.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 givereturn aux
. But it doesn’t suit me because he would be creating a copy and not a reference inGame.personagens.push(aux)
– Zano
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 } ] }
– Marcos ACR