Composition of objects in javascript

Asked

Viewed 229 times

1

I’m studying a little more javascript here and I’ve come 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 doesn’t work, because javascript through the prototype only accepts an inherited object, and in the example above I assign the two to prototype. If we try to call it that, "box. x" is a property of Shape2d:

console.log(Player.boxX);

I get a "Undefined". So I thought, I don’t want to use inheritance in this situation, and since I don’t like to create an inheritance ladder, I’d rather try to find other alternatives. I researched and saw about composition, but still do not understand how it would be in javascript, I think so:

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 that objects are different, that I don’t happen to change something in the Sprite object of one and end up changing in the other because I have just referenced. I would have to clone the objects to create that composition?

1 answer

0

I was studying until now, and I 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);

Browser other questions tagged

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