首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >S实例化作为参数传递的类。

S实例化作为参数传递的类。
EN

Stack Overflow用户
提问于 2022-02-09 12:19:15
回答 1查看 23关注 0票数 2

我试图实现一种简洁的方法来构建多个工厂(受植物和僵尸的启发)。为了更容易地添加更多的植物类型,我想使工厂的成本和dmg保持不变,这样我就可以为所有这种类型的工厂设置一次。

在这种情况下,我只有一个植物(向日葵),现在我想实例化向日葵植物。在单元格类中的构建方法中。

在这样做时,我得到了一个错误:Cannot create an instance of an abstract class.,这对我来说是可以理解的。那么,是否有一种方法只能将非抽象类作为build()方法的参数从if (!c isAbstract)扩展而来,还是必须实现某种if (!c isAbstract)

代码语言:javascript
复制
abstract class Plant {
  public static dmg: number;
  public static cost: number;

  constructor(cell: Cell) {
    this.cell = cell;
  }

  cell: Cell;
}

// I would like to create more Plants like this
class Sunflower extends Plant {
  public static dmg = 0;
  public static cost = 50;
  cell: Cell;

  constructor(cell: Cell) {
    super(cell);
  }
}

class Cell {
  build(c: typeof Plant) {
    if (c.cost <= game.money) {
      this.plant = new c(this); //Cannot create an instance of an abstract class.
      game.money -= c.cost;
    }
  }
}

// this is how I would build plants.
let c = new Cell();
c.build(Sunflower);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-09 12:29:22

你可以这样做:

代码语言:javascript
复制
class Cell {
    
  build<T extends Plant>(plant: (new (cell:Cell) => T)) {
    const plantInstance = new plant(this); 
  }
}

操场链接

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71049493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档