如何使用抽象构造函数来构建游戏对象?

时间:2018-01-22 15:12:28

标签: javascript function oop prototype

请帮我修复我的代码。在我的游戏中存在敌人物体和玩家物体。它们具有相同的属性:xCoord,yCoord。我试图从抽象构造函数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);

但是所有对象都没有属性:xCoords,yCoords

JSFIDDLE

1 个答案:

答案 0 :(得分:4)

您可以使用call方法并在parameters函数中传递PlayerShip

Ship.call(this, x,y);

调用parent's 构造函数初始化对象本身,这是在每次实例化时完成的(每次构造时都可以传递不同的参数)。

&#13;
&#13;
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);
&#13;
&#13;
&#13;