JavaScript Prototype Based Inheritance – Magic Revealed

JavaScript becomes more and more widely used language – not only for front-end but back-end (Node.js) too. Almost every web project contains thousands lines JS – layout and animations, AJAX calls etc. Talking about web we cannot skip the modern single page applications where all the user flow and server calls are controlled by the script language.

When we have so much logic implemeted in JavaScript we need a really good code structure, readability and reusability, don`t we?

Nothing can do this job better than the object oriented programming!

In JavaScript the object oriented concept is realized using JavaScript prototype. The simplest and probably most understandable explanation of prototype is:

In JavaScript the prototype is a shared object withing all the instances of a given class.

So we use this “shared object” to achieve inheritance.

In the image bellow I defined a class Animal

animal

The constructor takes a config object with age and name fields. Age is kept as a private class variable and name is stored as a public class field. Private scope in JS is achieved using var keyword. In this way “_age” lives just in the scope of constructor function Animal and behaves like a private class field. I defined two functions getAge and setAge to manipulate the private field “_age”. Have in mind that you can add functions and properties to the prototype of a given class outside it`s constructor:

function_outside

Note: Using this approach we do not have access to the private class field (in our case “_age”).

Now we have class Animal with one private and one public field and 3 functions.

Let`s inherit the Animal Class:

catclass
The key of inheritance here is the line:

Cat.prototype = new Animal();

Another words the prototype of the class Cat becomes and instance of the Animal class and in this way it has all its fields and functions.
One very important part of all the magic here is to pass the configuration object to the Animal constructor:

Animal.call(this, config);

I added function sayMiau and breed field just to show that Cat can have it`s own functions and fields.

Let`s do some tests of the written above:

test

In JavaScript we can even modify the prototype of native objects.
In the next example I extended the String prototype by adding the c#-like format function:

string_extension

You can see the code of all the examples here:
https://github.com/Bilyukov/javascript-oo-programming

Leave a Comment.