Simple Inheritance with JavaScript

Share this article

This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

A lot of my friends are C# or C++ developers. They are used to using inheritance in their projects and when they want to learn or discover JavaScript, one of the first question they ask is: “But how can I do inheritance with JavaScript?”

Actually, JavaScript uses a different approach than C# or C++ to create an object-oriented language. It is a prototype-based language. The concept of prototyping implies that behavior can be reused by cloning existing objects that serve as prototypes. Every object in JavaScript decends from a prototype which defines a set of functions and members that the object can use. There is no class. Just objects. Every object can then be used as a prototype for another object.

This concept is extremely flexible and we can use it to simulate some concepts from OOP like inheritance.

Implementing Inheritance

Let’s visualize what we want to create with this hierarchy using JavaScript:

JavaScript Inheritance Hierarchy

First of all, we can create ClassA easily. Because there are no explicit classes, we can define a set of behavior (A class so…) by just creating a function like this:

var ClassA = function() {
    this.name = "class A";
}

This “class” can be instantiated using the new keyword:

var a = new ClassA();
ClassA.prototype.print = function() {
    console.log(this.name);
}

And to use it using our object:

a.print();

Fairly simple, right?

The complete sample is just 8 lines long:

var ClassA = function() {
    this.name = "class A";
}

ClassA.prototype.print = function() {
    console.log(this.name);
}

var a = new ClassA();

a.print();

Now let’s add a tool to create “inheritance” between classes. This tool will just have to do one single thing: clone the prototype:

var inheritsFrom = function (child, parent) {
    child.prototype = Object.create(parent.prototype);
};

This is exactly where the magic happens! By cloning the prototype, we transfer all members and functions to the new class.

So if we want to add a second class that will be a child of the first one, we just have to use this code:

var ClassB = function() {
    this.name = "class B";
    this.surname = "I'm the child";
}

inheritsFrom(ClassB, ClassA);

Then because ClassB inherited the print function from ClassA, the following code is working:

var b = new ClassB();
b.print();

And produces the following output:

class B

We can even override the print function for ClassB:

ClassB.prototype.print = function() {
    ClassA.prototype.print.call(this);
    console.log(this.surname);
}

In this case, the produced output will look like this:

class B 
I’m the child

The trick here is to the call ClassA.prototype to get the base print function. Then thanks to call function we can call the base function on the current object (this).

Creating ClassC is now obvious:

var ClassC = function () {
    this.name = "class C";
    this.surname = "I'm the grandchild";
}

inheritsFrom(ClassC, ClassB);

ClassC.prototype.foo = function() {
    // Do some funky stuff here...
}

ClassC.prototype.print = function () {
    ClassB.prototype.print.call(this);
    console.log("Sounds like this is working!");
}

var c = new ClassC();
c.print();

And the output is:

class C 
I’m the grandchild 
Sounds like this is working!

More Hands-on with JavaScript

It might surprise you a bit, but Microsoft has a bunch of free learning on many open source JavaScript topics and we’re on a mission to create a lot more with Project Spartan coming. Check out my own:

Or our team’s learning series:

And some free tools: Visual Studio Community, Azure Trial, and cross-browser testing tools for Mac, Linux, or Windows.

And Some Philosophy…

To conclude, I just want to clearly state that JavaScript is not C# or C++. It has its own philosophy. If you are a C++ or C# developer and you really want to embrace the full power of JavaScript, the best tip I can give you is: Do not try to replicate your language into JavaScript. There is no best or worst language. Just different philosophies!

This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.

Frequently Asked Questions (FAQs) about JavaScript Inheritance

What is the difference between classical and prototypal inheritance in JavaScript?

In JavaScript, there are two types of inheritance: classical and prototypal. Classical inheritance, also known as constructor inheritance, is where a new object is created from a class or constructor function. This is similar to how inheritance works in languages like Java or C++. Prototypal inheritance, on the other hand, is unique to JavaScript. It involves creating a new object that inherits properties from an existing object. This is done using the Object.create() method or by setting the prototype of the new object to the existing object. The main difference between the two is that classical inheritance uses classes and constructor functions, while prototypal inheritance uses objects.

How does the prototype chain work in JavaScript inheritance?

The prototype chain is a crucial concept in JavaScript inheritance. When a property or method is accessed on an object, JavaScript first checks if that object has that property or method. If it doesn’t, JavaScript then checks the object’s prototype. This process continues up the prototype chain until the property or method is found or the end of the chain is reached (which is usually the built-in Object prototype). This mechanism allows objects to inherit properties and methods from their prototypes, enabling code reuse and inheritance in JavaScript.

Can you explain the concept of ‘super’ in JavaScript inheritance?

The ‘super’ keyword in JavaScript is used in the context of classes to call functions on an object’s parent. In other words, ‘super’ allows you to access and call functions on an object’s parent class, enabling you to reuse the parent class’s methods. This is particularly useful in the constructor of a subclass, where you might want to call the constructor of the parent class.

How can I override inherited methods in JavaScript?

Overriding inherited methods in JavaScript is straightforward. You simply define a method with the same name in the child class or object. When that method is called on an instance of the child class or object, the version defined in the child will be used instead of the one in the parent. This allows you to customize or extend the behavior of inherited methods.

What is the role of the ‘constructor’ in JavaScript inheritance?

The ‘constructor’ in JavaScript is a special method that is used to create and initialize an object. In the context of inheritance, the constructor function of the parent class is often called in the constructor of the child class using the ‘super’ keyword. This allows the child class to inherit the properties and methods of the parent class.

How does inheritance work with JavaScript ES6 classes?

With the introduction of ES6, JavaScript now has a more traditional class-based syntax for defining constructors and working with inheritance. The ‘class’ keyword is used to define a class, and the ‘extends’ keyword is used to create a subclass that inherits from a parent class. The ‘super’ keyword is used in the constructor of the subclass to call the constructor of the parent class.

Can you explain multiple inheritance in JavaScript?

JavaScript does not natively support multiple inheritance, where an object or class can inherit from more than one parent. However, it is possible to simulate multiple inheritance using mixins. A mixin is a technique where an object or class can “mix in” properties and methods from multiple sources. This allows you to combine the functionality of multiple objects or classes into one.

What is the difference between ‘inheritance’ and ‘composition’ in JavaScript?

Inheritance and composition are two ways to reuse code in JavaScript. Inheritance is where an object or class inherits properties and methods from a parent object or class. Composition, on the other hand, is where an object is composed of other objects, and functionality is delegated to these component objects. While inheritance is about an “is-a” relationship (a subclass is a type of the parent class), composition is about a “has-a” relationship (an object has other objects).

How can I use inheritance with JavaScript functions?

Functions in JavaScript are objects, and they can be used to implement inheritance. This is done by defining a constructor function, which is used to create new objects. The ‘prototype’ property of the constructor function is an object that all instances of the function will inherit from. By adding properties and methods to this prototype object, you can make them available to all instances of the function.

What are some common pitfalls of JavaScript inheritance?

One common pitfall of JavaScript inheritance is the confusion between the prototype chain and the constructor chain. When a method is called on an object, JavaScript looks up the prototype chain, not the constructor chain. Another pitfall is forgetting to call the parent constructor in the child constructor, which can lead to unexpected results. Finally, because JavaScript uses prototypal inheritance, it’s possible to accidentally modify the prototype when you meant to modify an instance.

David CatuheDavid Catuhe
View Author

David Catuhe is a Principal Program Manager at Microsoft focusing on web development. He is author of the babylon.js framework for building 3D games with HTML5 and WebGL. Read his blog on MSDN or follow him on Twitter.

javascript inheritanceMDC
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week