javascript - 是否可以从另一个类中调用一个类(不扩展)?

标签 javascript

我正在为一款基本游戏开发不同的组件。

现在我的结构是我有一个种族类文件,该文件导出到另一个文件,其中我有一个类从人类延伸出来并成为玩家。为玩家提供人类和玩家的属性。

但是,这意味着如果我想制作一个非人类的玩家,我将不得不制作一个新的玩家类别,从不同的种族中延伸出来。这似乎是一种糟糕的做法,我想找到一种方法来重构它以使其更好地流动。


这是我的人类类(class):

export class Human {
constructor() {
    this.type = 'Human';
    this.health = 10;
    this.baseAttack = 2;
    this.baseDefense = 1;
}

这是我的播放器播放器类:

export class Player extends Human {
constructor(name, level){
    super();
    var inventory = {};
    this.name = name;
    this.level = level;
    this.inventory = inventory;
    this.currentCapacity = 0;
    this.maxCapacity = 50;
}

Player 类中还有其他与库存相关的函数,但这些函数似乎与我的问题无关。


我的预期结果是我有一组种族,当我制作玩家或 Angular 色时,我可以从该组中选择,然后该玩家或 Angular 色将继承该种族的静态属性(例如健康、基础攻击、和 baseDefense)。

最佳答案

正如聪明的 child 所说,更喜欢组合而不是继承。你可以做这样的事情而不会偏离你当前的方法太远:

class Orc {
  constructor() {
    this.mortal = true
  }
}

class Player {
constructor(race, name, level){
    var inventory = {};
    this.race = race;
    this.name = name;
    this.level = level;
    this.inventory = inventory;
    this.currentCapacity = 0;
    this.maxCapacity = 50;
    }
}

const orc = new Player(new Orc(), 'Baz', 1 )
console.log(orc.race)

有很多其他方法可以给这只猫剥皮,包括让人类从 Player 传下来。事实上,这将是使用经典继承对这些实体建模的常用方法(玩家是一般情况,人类和兽人更具体)。

class PlayerClassic {
constructor(name, level){
    var inventory = {};
    this.name = name;
    this.level = level;
    this.inventory = inventory;
    this.currentCapacity = 0;
    this.maxCapacity = 50;
    }
}


class Human extends PlayerClassic {
  constructor(name, level) {
    super(name, level)
    this.mortal = true
  }
}

const human = new Human('Johnny', 2)
console.log(human)

我发现继承层次结构很少有好处。在上述两种情况下,您都必须使用 typeof 来确定您正在处理的是哪种生物。

如果是我的代码,我可能会完全跳过这些类(class)。我可能会做类似下面的事情来构建一个代表一个构建的玩家的数据结构:

const raceTemplates = {
  human: {mortal:true}, 
  elf: { mortal:true}}

const playerMaker = template => (race, name, level)=> {
  return {
    name,
    level,
    race,
    inventory: {},
    currentCapacity:0,
    maxCapacity:50,
    ...template[race]
  }
}  

const player = playerMaker(raceTemplates)('elf', 'sammy', 2)
console.log(player) 

这里有一个 repl.it 的链接,供任何感兴趣的人使用:

https://repl.it/@rmoskal/RealisticWholeParameter

关于javascript - 是否可以从另一个类中调用一个类(不扩展)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55409402/

相关文章:

javascript - jQuery 滚动到页面底部锁定/断断续续/抖动滚动

java - JSF SelectOneRadio 按钮无法禁用

javascript - 如何重命名handsontable.js 中的上下文菜单项?

javascript - 在工厂函数中使用扩展而不是类 `extends`

javascript - php根据html切换开关显示数据库中的数据

javascript - 将字符串转换为标准矩格式

php - 如何使用 JavaScript 和 PHP 来存储变量?

javascript - Ext.data.NodeInterface 禁用属性

javascript - 如何在 JavaScript 中的 Y 和 Z 范围内随机生成 X 个数字?

javascript - 用于 firebase 的 Cloud Functions 返回响应 500