Implementing Single Inheritance In JavaScript

Our first goal is to implement single inheritance in a manner similar to Java, and provide a compact way to declare a new class. JavaScript provides an inheritance mechanism based on prototype chaining as illustrated in Figure 2. In this example, aRectangle is an instance of Rectangle. Since Rectangle extends Shape, aRectangle is also an instance of Shape.


Figure 2 - Prototypal Inheritance In JavaScript

Each JavaScript object has a reference to its prototype called __proto__. This is the prototype of the constructor that created the object. In this example, aRectangle's prototype is the prototype of Rectangle. The prototype for Rectangle is an instance of Shape, so the prototype of Rectangle's protoype is the prototype of Shape. When a script calls aRectangle.draw, the interpreter searches first in aRectangle, then follows the prototype chain until it finds a draw method in aRectangle's prototype. When a script calls aRectangle.select, the interpreter follows the prototype chain until it finds a select method in Shape's prototype.

Java has no prototypes but the result is similar. The compiler keeps track of which methods are implemented by each class and walks up the inheritance tree until it finds a class that implements the method. One noticable difference is during the creation of an object. When an object is created in Java, the constructors of the class and all base classes are called beginning with the constructor for the most distant ancestor. In our example, when aRectangle was created using the new operator, the interpreter only calls the Rectangle constructor.

Next we look at how to chain constructors together to make our JavaScript classes behave more like Java.