简体   繁体   中英

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).

I wouldn't make such distinctions and rely on inheritance at all. I would prefer composition over inheritance so I am not locked in my inheritance box when a change comes. Also consider premature overengineering in this case, do you really expect performance issues by storing these properties in the object itself? My Design would be that you have a Character which is either is with x, y, hearts, width, height, leftMargin, topMargin, type properties. So in this way you have very flexible consistent data which will match your future requirements:

  • Enemies can turn in Friends by changing type
  • Enemies can also have hearts at certain point in time, why they shouldn't?
  • all Characters can grow/shrink by changing width/height
  • all Characters can change position by changing margin.

Basically you will have a universal data structure to manipulate with without pulling your hairs out to maintain your hierarchy model. Hope this will help you.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM