gpt4 book ai didi

javascript - 如何为游戏对象使用抽象构造函数?

转载 作者:行者123 更新时间:2023-11-30 09:27:36 25 4
gpt4 key购买 nike

请帮助修复我的代码。在我的游戏中存在敌人对象和玩家对象。它们具有相同的属性: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

最佳答案

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

Ship.call(this, x,y);

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

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

关于javascript - 如何为游戏对象使用抽象构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48384704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com