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?