Object oriented JavaScript – Inheritance

Creating hierarchy of classes in JavaScript is much more different then in languages like Java and C++. There is no notion of classes, only objects and prototypes. This can be a little confusing, and requires a shift from mindset if you come from Java/C++ background. In this post, I will try to show how to implement inheritance hierarchy in JavaScript.

Inheritance sample

We will create simple hierarchy in which we have a base class Vehicle , and a subclass RoadVehicle  which extends it. First, will create base class. If you have trouble understanding object creation, see the topic on that in previous post.

Here, we create a prototype for Vehicle  object, along with some properties and methods. We then create an object of Vehicle  type. Now is the time to create subclass.

As you can see, there’s no special syntax to specify extension of objects. The magic happens in line 9, where we create RoadVehicle  prototype. We basically clone Vehicle  prototype, thus copying all of it’s properties and methods to RoadVehicle . Also note that we call superclass constructor in line 4. This is not a requirement, but since base class takes parameters for construction, we need to call it to initialize super class properties.

You may also note that subclass inherits all properties and methods from it’s super class. In JavaScript, there is no access modifiers like private/protected. There are ways to achieve private access, like using closures, but I will not cover them in this post. If interested, you may find a lot of reading online, like this article.

Overriding superclass methods

Once methods are inherited in subclasses, we can overrride them to get different behavior. Consider the following snippet:

To override method, you simply redefine it in subclass prototype, as shown in line 2. You can also call superclass methods from subclass, as shown in line 10. To do this, we use Superclass.prototype.function.call(this,args)  syntax.

This is about all for JavaScript inheritance. In the next post, I will cover another cornerstone of object oriented programming – encapsulation.

Complete source code for all samples in this post can be found at Github repository.

Related posts:

One thought on “Object oriented JavaScript – Inheritance

Leave a Reply

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