请帮助修复我的代码。在我的游戏中存在敌人对象和玩家对象。它们具有相同的属性: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
吉斯菲德尔
您可以使用
call
方法并在PlayerShip
函数中传递parameters
。
Ship.call(this, x,y);
调用 parent's
构造函数会初始化对象本身,这是通过每次实例化完成的(每次构造它时都可以传递不同的参数(。
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);