Search code examples
javascriptfunctionoopprototype

How use abstract constructor for game objects?


Please help fix my code. In my game exists enemies objects and player object. They have the same properties: xCoord, yCoord. I'm trying to inherit these properties from the abstract constructor Ship():

var player,
    enemies = [],
    enemiesCntInit = 10;

function Ship(x, y) {
  this.xCoord = x;
  this.yCoord = y;
};

function PlayerShip(x, y) {
  this.petrol = 100;
};  

function EnemyShip(x, y) {  
  this.color = 'red';
}; 

PlayerShip.prototype = Object.create(Ship.prototype);


player = new PlayerShip(100, 100); 

for(var i = 0; i < enemiesCntInit; i++) {
  enemies.push(new EnemyShip(0, 0));
}

console.log(player);
console.log(enemies);

But all objects do not have properties: xCoords, yCoords

JSFIDDLE


Solution

  • You can use call method and pass your parameters inside the PlayerShip function.

    Ship.call(this, x,y);
    

    Calling the parent's constructor initializes the object itself, this is done with every instantiation (you can pass different parameters each time you construct it).

    var player,
        enemies = [],
        enemiesCntInit = 10;
    
    function Ship(x, y) {
      this.xCoord = x;
      this.yCoord = y;
    };
    
    function PlayerShip(x, y) {
      Ship.call(this, x,y);
      this.petrol = 100;
    };  
    
    function EnemyShip(x, y) {  
      Ship.call(this, x,y);
      this.color = 'red';
    }; 
    
    PlayerShip.prototype = Object.create(Ship.prototype);
    
    
    player = new PlayerShip(100, 100); 
    
    for(var i = 0; i < enemiesCntInit; i++) {
      enemies.push(new EnemyShip(0, 0));
    }
    
    console.log(player);
    console.log(enemies);