Inheritance in Javascript

inheritance, interface, javascript, oop, prototype

Solution

Take a look at Douglas Crockford's articles:

- Prototypal Inheritance in JavaScript

- Private Members in JavaScript

- Classical Inheritance in JavaScript

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

These articles are must-reads, and I'm sure they will help you figure out how to structure your objects.

Problem

I am working on a simple problem to represent a few types that have a hierarchical structure. There is a data row that contains some data, and the data could vary from type type of row to another. A simple row might only have a title and date, while an extended row may contain a title, description, date and an image. I am not new to Javascript but don't understand it well enough to proceed forward. To give a simplified example, here is how I would write it in 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 } } ``` There are few OO improvements that can be done here such as extending ExtendedRow from BasicRow and only defining the new fields plus overriding the getView method. Javascript does not have interfaces or abstract classes and I am afraid I haven't gone down to thinking in a prototypical sense yet. So how could I go about implementing something as basic as the above example in Javascript where there is a base class or an interface, and two classes extending from that base class, each with their own specific behavior. Any pointers are greatly appreciated.

Original source