javascriptdesign-patternsprototype-chainprototype-pattern

Refactoring objects with the same prototype properties


Let's say we have a superclass Character and 2 subclasses Player and Enemy.

var Character = function(x, y){
    this.x = x || 0;
    this.y = y || 0;
};
var Enemy = function() {
    // randomInt returns an integer value in between 0 and 505 (canvas width)
    var x = randomInt(0, 505);
    var y = this.getNewRow();
    Character.call(this, x, y);
};
var Player = function(x, y, hearts) {
    Character.call(this, x, y);
    this.hearts = hearts;
};

Both Player and Enemy will have prototype properties such as width, height, leftMargin, and a topMargin.

Enemy.prototype.width = 96; 
Enemy.prototype.height = 65; 
Enemy.prototype.leftMargin = 2; 
Enemy.prototype.topMargin = 78; 

Player.prototype.width = 66; 
Player.prototype.height = 75;
Player.prototype.leftMargin = 18;
Player.prototype.topMargin = 64; 

Since both subclasses Player and Enemy have these 4 properties (with different values nonetheless), I feel like this should be refactored somehow, but how? Since every instance of these classes will have the same property values, I do want to leverage the prototype chain and keep them in a prototype object (unless you can explain to me why I shouldn't do this).


Solution

  • There is no special design pattern to apply here. Putting these properties on the respective prototypes is fine, you might even want to put some defaults on Character.prototype. Since they are properties for instances which should be shared by all objects of a class, the prototype is exactly the right place to put them.

    If you want to avoid repetition when assigning them, just put that in a function.