javascript - 如何在typescript中模拟多态?

标签 javascript inheritance polymorphism

我正在尝试在 typescript 中模拟 OOP 概念。我有 Java 背景。我面临的问题是,我正在尝试创建一款棋盘游戏。我有酒店、 jail 、宝藏等细胞类型。它们都有一个共同的属性,称为类型数的数量。所以我创建了一个名为 CellType 的接口(interface)并将其实现到上面提到的各个类(酒店、宝藏等) 有一个名为 Board 的类,我想在其中初始化并声明预定义单元类型的数组。像这样的事情:

var cell[:CellType]; //declaration
Hotel = new Hotel(200);
cell = [Hotel1,Treasure1,Jail1,Hotel2..] //initialization

在java中我们可以做到:

interface CellType{ public integer amount};
class Hotel implements CellType;
class Jail implements Celltype;
// in main class
ArrayList<CellType> cellTypes = new ArrayList<CellType>;
Hotel Taj = new Hotel();
cellTypes.add(Taj);
Jail jail = new Jail();
cellTypes.add(jail);

那么,如何像 Java 中那样声明继承同一个父类(super class)的多个子类的数组?

最佳答案

接口(interface)/类:

interface CellType { amount: number };

class Hotel implements CellType { 
  // This concise syntax creates the public property
  // and assigns to it the value passed into the
  // constructor
  constructor(public amount: number) { }
}

class Jail implements CellType {
  constructor(public amount: number) { }
}

用法:

let cellTypes: Array<CellType> = []; // Or let cellTypes: CellType[] = [];

let taj = new Hotel(100);
cellTypes.push(taj);
let jail = new Jail(200);
cellTypes.push(jail);

你可以这样更简洁:

let cellTypes: Array<CellType> = [new Hotel(100), new Jail(200)];

关于javascript - 如何在typescript中模拟多态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097929/

相关文章:

C++ | DLL/EXE - 如何从导出类中调用另一个类方法?

c++ - 排序对象和多态性

c++ - 返回bitset的成员函数,继承自基类

javascript - 为什么 Promise.all(..) 在附加的 then 处理程序中传递未解决/待处理的 promise ?

javascript - 在 Chrome 54 中扩展内置元素时无法创建自定义元素

java - 在类中调用方法,即使它已在子类中被覆盖(java)

java - java层次结构不明确

javascript - 如何在页面重新加载后保留变量的值?

javascript - Backbone.js 解析方法

java继承的最佳实践?