【发布时间】:2011-01-02 21:15:54
【问题描述】:
我正在研究一个简单的问题来表示一些具有层次结构的类型。有一个数据行包含一些数据,数据可能因行的类型而异。简单的行可能只有标题和日期,而扩展的行可能包含标题、描述、日期和图像。我对 Javascript 并不陌生,但对它的理解还不够好,无法继续前进。举一个简化的例子,下面是我用 Java 编写它的方式:
interface Row {
View getView();
}
class BasicRow implements Row {
private String title;
private String description;
public BasicRow(String title, String description) {
this.title = title;
this.description = description;
}
public View getView() {
// return a View object with title and description
}
}
class ExtendedRow implements Row {
private String title;
private String description;
private Date date;
private Image image;
public ExtendedRow(String title, String description, Date date, Image image) {
this.title = title;
this.description = description;
this.date = date;
this.image = image;
}
public View getView() {
// return a View object with title
// description, date, and image
}
}
这里可以进行的 OO 改进很少,例如从 BasicRow 扩展 ExtendedRow 并仅定义新字段并覆盖 getView 方法。
Javascript 没有接口或抽象类,恐怕我还没有深入到原型意义上的思考。那么我该如何在 Javascript 中实现与上面示例一样基本的东西,其中有一个基类或接口,以及从该基类扩展的两个类,每个类都有自己的特定行为。
非常感谢任何指针。
【问题讨论】:
标签: javascript inheritance oop prototype interface