【问题标题】:How use abstract constructor for game objects?如何为游戏对象使用抽象构造函数?
【发布时间】:2018-01-22 15:12:27
【问题描述】:

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

【问题讨论】:

  • 你永远不会在Ship 中调用构造函数——它绝不是自动的。 vanilla javascript中的继承与您期望的不同。尝试阅读以下内容:markdalgleish.com/2012/10/…
  • 要记住的一件事...... JS 并不真正支持继承。至少,如果来自 Java 或 C# 或大多数其他面向对象的语言,这不是您习惯的方式。你需要仔细重新考虑你的范式,或者考虑像 TypeScript 这样的 JS 超集语言,它可以为你实现这些范式。见typescriptlang.org/docs/handbook/classes.html

标签: javascript function oop prototype


【解决方案1】:

您可以使用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);

【讨论】:

  • 但我需要创建玩家和敌人。 2 类对象
  • @provoter33,是的,在PlayerShip 方法中调用相同的函数。
猜你喜欢
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多