Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / Javascript
Article

Simple inheritance with JavaScript

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Apr 2015CPOL3 min read 12.3K   13   1
A lot of my friends are C# or C++ developers. They use inheritance in their projects and when they want to learn or discover JavaScript, one of the first questions they ask is: “But how can I do inheritance with JavaScript?”

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

A lot of my friends are C# or C++ developers. They are used to use 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 depends 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 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 image what we want to create with this hierarchy using JavaScript:

First of all, we can create ClassA easily. Because there is 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: Cloning 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 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 lie this:

class B
I’m the child

The trick here is to 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 Microsoft Edge 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 Microsoft Edge and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @  modern.IE.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
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 @deltakosh on Twitter.

Comments and Discussions

 
QuestionNice Artile Pin
Silence Peace5-May-15 8:24
Silence Peace5-May-15 8:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.