Using Composition
by Neviton
JavaScript
var Resizable = function() {
return {
resize: function(dw, dh) {
this.width += dw;
this.height += dh;
console.log('resize:', this.width, this.height);
}
}
},
Movable = function() {
return {
move: function(dx, dy) {
this.x += dx;
this.y += dy;
console.log('move:', this.x, this.y);
}
}
},
Transformable = function() {
return Object.assign (
{
getRect: function() {
return {
top: this.y,
right: this.x + this.width,
bottom: this.y + this.height,
left: this.x
}
},
getPosition() {
return {
x: this.x,
y: this.y
}
}
},
Movable(),
Resizable()
);
},
Enemy = function() {
return Object.assign(
{
x: 0,
y: 0,
width: 50,
height: 30
},
Transformable()
);
};
var goblin = Enemy();
goblin.move(5, 3);
goblin.move(1, 0);
goblin.move(0, -1);
console.log(goblin.getRect());