1
I have a question maybe a little stupid, but come on, in Javascript, I can create an instance of an object declaring like this, let’s go in an example of a game, where I have to instate bullets to shoot the enemy:
var Bala = {
myFunctionInit: function myFunctionInit(){
console.log("Pul!");
},
x = 0,
y = 0,
speed = 0
};
but then I want to be able to instantiate several of those bullets, but I can’t do something like:
var outraBala = new Bala;
and I understand why I can’t, because the Bullet is already an instantiative object, that I could see giving a "console.log(Bullet);", the question is, how can I instantiate the Bullet, correctly declaring objects in this way?
I know what I can do:
var outraBala = Object.assign({}, Bala);
I also thought about putting the literal object Bala as a return of a function, and so be able to instantiate it like this:
var Bala = function(x, y, speed) {
return = {
myFunctionInit: function myFunctionInit(){
console.log("Pul!");
},
x: x,
y: y,
speed: speed
};
}
var outraBala = Bala(1, 1, 10);
but I’m not sure if it’s the best way to deal with this situation.
BS: I don’t want to instantiate objects using class, that way I know how to do it, I want to be able to create them in this declarative way (which I personally think is the clearest of all) and instate them in the best way possible, and if it is my stupidity, I need to understand why.
You want to instantiate an object several times, it would not be the case of a constructor function?
– Costamilam
@Guilhermecostamilam like the one I made(
var Bala = function(x, y, speed) {...
)?– PerduGames
With some corrections, the function you made receives 3 parameters but does not use them instead of
=
is:
inside the returned object– Costamilam
@Guilhermecostamilam corrected there, I even traveled with the "=" and forgot to assign the parameters XD
– PerduGames