Classical Inheritance in Javascript

It’s amazing how flexible JavaScript is–it can do anything! It can even do OOP. As our JS implementations become more and more complicated, it’s great that ECMAScript allows us utilize the power of OOP, which should help us with code maintainability, re-use, and task-division. Although interfaces aren’t practical in a dynamic language that encouraged duck-typing, we can still take advantage of controlling variable scope (topic for another day), classes, and (pseudo) inheritance. In this article, I will go over one method of implementing classes and later I will talk about how to inherit that class in a new one. What I present in this article is one way of implementing classes with some variations of syntax, but because of the language’s flexibility, other methods exist as well.

Creating a Class

First we create the construct for a vehicle class. This will get run as soon as an object is created based on that class:

// Create new class to work with to better show the example
var Vehicle = function vehicle(model,type,totalWheels)

Next we implement the getter and setter functions for the properties of our Vehicle class. Note that above, I already use the setter methods in my object, but alternatively you can call “this.model = model;” directly in the constructor. Here is how we implement the getter and setter methods:

// Setter methods for the class
Vehicle.prototype.setModel = function(model)
  this.model = model;

Vehicle.prototype.setType = function(type)
  this.type = type;

Vehicle.prototype.setTotalWheels = function(wheels)
  this.totalWheels = wheels;

// Get method that returns a string.
Vehicle.prototype.getVehicle = function()
  return this.model + " " + this.type  + " with " + this.totalWheels + " wheels"; 

The first two methods set an object’s attributes and can be run on the object itself at any time. The second is a method that returns a phrase that describes the object. If you need to return each individual attribute, you would simply do the opposite of the first 3 setter methods.

One thing to note is that the object’s attributes are NOT private–you can always access them with [object].[attribute]. There is a way to hide these attributes (using closures) to follow the open-closed principle, but I’ll leave that for another article.

Inheriting from the Class

ECMAScript only supports single class inheritance; essentially you can create a more specialized form of the parent class. In this example, I’m going to create a “Sedan” class based on the “Vehicle” class:

var Sedan = function(model,safetyRating)
  this.safetyRating = safetyRating;, model,"Sedan",4);

// Here we point to the first class (Vehicle) and the constructor is Sedan
Sedan.prototype = new myExamples.Vehicle();
Sedan.prototype.constructor = myExamples.Sedan;

Now I am creating a child class of the Vehicle class. In this example, I choose to automatically set some parameters for Sedan. For example, a Sedan will always be of type “Sedan” and have 4 wheels. As well, to illustrate how you can extend the parent class, I add a new attribute: safetyRating. This time, I don’t have a setter method for the “safetyRating” to illustrate the other way you can initialize an object parameter with the constructor.

Creating Objects

Finally we can create objects based on the above two classes. This is very simple and you use the constructors that we created:

// Create an object of the parent class "Vehicle"
var someVehicle = new Vehicle("MAK","Truck",18);
// Create an object of the child class "Sedan"
var subaruSedan = new Sedan("Subaru", "5/5");

// Check inheritance
var isSubaruSedan = subaruSedan instanceof this.Sedan;        // True
var isSubaruVehicle = subaruSedan instanceof this.Vehicle;    // True
var isTruckSedan = someVehicle instanceof this.Sedan;         // False

In the above example I create an instance of Vehicle and an instance of Sedan. In the sedan instance I have all of the methods and attributes available in Vehicle and Sedan class, while the vehicle instance only has the methods and attributes of vehicle.

My JsFiddle Example

ECMAScript is a prototype based language that does not include OOP specific statements. For example, it doesn’t have “class” or “extends” or “inherits” … however, the language is so versatile we can still have classes and inheritance (albeit limited).

I should also say that it’s possible to recreate OOP syntax more closely by creating a dummy class constructor, methods, etc. John Resig wrote an excellent article and re-usable script (MIT Liscence). Check out his article here.

Reference Links:
Introduction to Object-Oriented JavaScript
John Resig – Simple JavaScript Inheritance

Leave a Reply

Your email address will not be published. Required fields are marked *