javascript - Javascript 中的继承

标签 javascript inheritance oop prototype interface

我正在研究一个简单的问题来表示一些具有层次结构的类型。有一个包含一些数据的数据行,数据可能因行类型而异。简单行可能只有标题和日期,而扩展行可能包含标题、描述、日期和图像。我不是 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 没有接口(interface)或抽象类,恐怕我还没有深入到原型(prototype)意义上的思考。那么,我如何才能在 Javascript 中实现与上面示例一样基本的东西,其中有一个基类或一个接口(interface),以及从该基类扩展的两个类,每个类都有自己的特定行为。

非常感谢任何指点。

最佳答案

看看 Douglas Crockford 的文章:

Douglas Crockford is a senior JavaScript architect at Yahoo! He is well known for his work in introducing JavaScript Object Notation (JSON) - Wikipedia

这些文章是必读,我相信它们会帮助您了解如何构建对象。

关于javascript - Javascript 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2027166/

相关文章:

javascript - 如何检查ios是否正在使用隐私浏览

javascript - 在 jQuery 中最接近的不起作用

javascript - 从 AS3 客户端运行 MongoDB 查询?

php - OOP 或结构 : PHP Web site

java - Servlet 以 Ajax 方式向网页发送双引号

java - 接口(interface)、继承和子类型

html - 为什么不显示: flex property being inherited to child divs?

javascript - 扩展 UI 选择 Controller ( Angular )

C# 面向对象 : Using interface with type parameters in base concrete class

javascript - LeafletJS 面向对象的最佳方法