How to instantiate objects using literal object syntax?

1

I have a question maybe a little stupid, but come on, in Javascript, I can create an instance of an object stating thus, let's go in an example of a game, where I have to install bullets to shoot at 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 these bullets, however I can not do something like:

var outraBala = new Bala;

and I understand why I can not, because the Bullet is already an object instance, this I could see giving a "console.log (Bullet);", the question is, how can I instantiate the Bullet, correctly declaring objects This way?

I know what I can do:

var outraBala = Object.assign({}, Bala);

I also thought of putting the Bullet literal object as the return of a function, so I could 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 handle this situation.

obs: I do not want to instantiate objects using class, this 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 instantiate them in the best possible way , and if it's stupid of me, I need to understand why.

    
asked by anonymous 14.07.2018 / 02:08

1 answer

1

As you said you do not want to use class of javascript you will have to do a constructor function, to instantiate you have some options:

Use the new operator:

function Bala(x, y, speed) {
  this.x = x;
  this.y = y;
  this.speed = speed;
}

let bala1 = new Bala(0, 0, 10);
let bala2 = new Bala(5, 5, 20);
let bala3 = new Bala(3, 0, 1);

console.log(bala1, bala2, bala3);

Return the object directly (I believe this is what you want):

function Bala(x, y, speed) {
  return {
    x: x,
    y: y,
    speed: speed
  };
}

let bala1 = Bala(0, 0, 10);
let bala2 = Bala(5, 5, 20);
let bala3 = Bala(3, 0, 1);

console.log(bala1, bala2, bala3);

Both will be the same, since, under the wipes, the new operator takes the this of the contracting function, ie the first example is equivalent to:

function Bala(x, y, speed) {
  let object = {};
  object.x = x;
  object.y = y;
  object.speed = speed;

  return object;
}

let bala1 = Bala(0, 0, 10);
let bala2 = Bala(5, 5, 20);
let bala3 = Bala(3, 0, 1);

console.log(bala1, bala2, bala3);
    
15.07.2018 / 17:22