Composing objects in javascript

1

I'm studying a little more javascript here and I came to a problem:

I have an object called player:

let Player = function () {
    this.name = 'player';
}

Player.prototype = new Sprite();
Player.prototype = new Shape2D();

That's what I try to do, and it does not work, because javascript through prototype only accepts an inherited object, and in the example above I assign both prototype. If we try to call it like this, "box.x" is a Shape2D property:

console.log(Player.boxX);

I get an "undefined". So I thought, I do not want to use inheritance in this situation, and since I do not like to create inheritance ladder, I'd rather try to find other alternatives. I researched and saw about composition, but I still do not understand what it would look like in javascript, I think like this:

let Player = function () {
    this.name = 'player';
    this.sprite = new Sprite();
    this.shape2D = new Shape2D();
}

or

let Player = function () {
    this.name = 'player';
}

Player.prototype.sprite = new Sprite();
Player.prototype.shape2d = new Shape2D();

or

let Sprite = {x:0, y:0}; 
let Shape2D = {x:0, y:0, width:0, height:0};
let Player = Object.assign(Sprite, Shape2D); // Sendo Sprite e Shape2D agora objetos literais

How to do this in the cleanest way possible?

obj1 = new Player();
obj2 = new Player();

Would obj1 be equal to obj2? I need a way in which the objects are different, that I do not happen to change something in the sprite object of one and end up changing in another because I have just referenced. Would I have to clone the objects to create this composition?

    
asked by anonymous 20.07.2018 / 21:23

1 answer

0

I was studying so far, and found the way to write and solve the problem that I find most pleasing to me:

const Sprite = (x=0, y=0) => ({
  x: x,
  y: y
});

const Shape2D = (x=0, y=0, width=0, height=0) => ({
  x: x,
  y: y,
  width: width,
  height: height
});

const spritePlayer = Sprite(0, 0);
const shape2DPlayer = Shape2D(0, 0, 32, 32);

let Player = Object.assign({}, spritePlayer, shape2DPlayer);
    
21.07.2018 / 06:49