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

How to implement inheritance in JavaScript

Rate me:
Please Sign up or sign in to vote.
4.40/5 (4 votes)
23 Dec 2011CPOL2 min read 54.6K   14   6
JavaScript hasn't got built-in inheritence but there is a workaround for this.

Introduction

If you have done Object Oriented Programming in JavaScript, you will know that you can create a class as follows:

JavaScript
Person = function(id, name, age){
    this.id = id;
    this.name = name; 
    this.age = age;

    alert('A new person has been accepted');
}

So far our class Person only has two properties and we are going to give it some methods. A clean way of doing this is to use its 'prototype' object.

Starting from JavaScript 1.1, the prototype object was introduced in JavaScript. This is a built in object that simplifies the process of adding custom properties and methods to all instances of an object.

Let's add two methods to our class using its 'prototype' object as follows:

JavaScript
Person.prototype = {
    /** wake person up */
    wake_up: function() {
        alert('I am awake');
    },


    /** retrieve person's age */
    get_age: function() {
        return this.age;
    }
}

Now we have defined our class Person. What if we wanted to define another class called Manager which inherits some properties from Person? There is no point redefining all these properties again when we define our Manager class, we can just set it to inherit from the class Person.

JavaScript doesn't have built-in inheritance but we can use a technique to implement inheritance as follows:

JavaScript
Inheritance_Manager = {};//We create an inheritance manager class (the name is arbitrary)

Now let's give our inheritance class a method called Extend which takes the baseClass and subClassas arguments. Within the Extend method, we will create an inner class with a function inheritance() { }. The reason why we are using this inner class is to avoid confusion between the baseClass and subClass prototypes.

Next we make the prototype of our inheritance class point to the baseClass prototype as in the following code:

JavaScript
inheritance.prototype = baseClass. prototype;

Then we copy the inheritance prototype into the subClass prototype as follows:

JavaScript
subClass.prototype = new inheritance();

The next thing is to specify the constructor for our subClass as follows:

JavaScript
subClass.prototype.constructor = subClass;

Once finished with our subClass prototyping, we can specify the next two lines of code to set some base class pointers.

JavaScript
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;

Here is the full code for our Extend function:

JavaScript
Inheritance_Manager.extend = function(subClass, baseClass) {
    function inheritance() { }
    inheritance.prototype = baseClass.prototype;
    subClass.prototype = new inheritance();
    subClass.prototype.constructor = subClass;
    subClass.baseConstructor = baseClass;

    subClass.superClass = baseClass.prototype;
}

Now that we have implemented our inheritance, we can start using it to extend our classes. In this case, we are going to extend our Person class into a Manager class as follows:

We define the Manager class:

JavaScript
Manager = function(id, name, age, salary) {
    Person.baseConstructor.call(this, id, name, age);
    this.salary = salary;
    alert('A manager has been registered.');
}

We make it inherit form Person:

JavaScript
Inheritance_Manager.extend(Manager, Person);

If you have noticed, we have just called the Extend method of our Inheritance_Manager class and passed the subClass Manager in our case and then the baseClass Person. Note that the order is very important here. If you swap them, the inheritance will not work as you intended if at all.

Also note that you will need to specify this inheritance before you can actually define the subClass.

Now let us define the subClass:

We can add more methods as shown below. Our Manager class will always have the methods and properties defined in the Person class because it inherits from it.

JavaScript
Manager.prototype.lead = function(){
   alert('I am a good leader');
}

Now to test it, let us create two objects, one from the class Person and one from the inherited class Manager:

JavaScript
var p = new Person(1, 'Joe Tester', 26);
var pm = new Manager(1, 'Joe Tester', 26, '20.000');

Here is the full JavaScript code you can copy:

JavaScript
Person = function(id, name, age){
    this.id = id;
    this.name = name;
    this.age = age;
    alert('A new person has been accepted');
}

Person.prototype = {
    /** wake person up */
    wake_up: function() {
        alert('I am awake');
    },

    /** retrieve person's age */
    get_age: function() {
        return this.age;
    }
}

Inheritance_Manager = {};

Inheritance_Manager.extend = function(subClass, baseClass) {
    function inheritance() { }
    inheritance.prototype = baseClass.prototype;
    subClass.prototype = new inheritance();
    subClass.prototype.constructor = subClass;
    subClass.baseConstructor = baseClass;
    subClass.superClass = baseClass.prototype;
}

Manager = function(id, name, age, salary) {
    Manager.baseConstructor.call(this, id, name, age);
    this.salary = salary;
    alert('A manager has been registered.');
}

Inheritance_Manager.extend(Manager, Person);

Manager.prototype.lead = function(){
   alert('I am a good leader');
}

var p = new Person(1, 'Joe Tester', 26);
var pm = new Manager(1, 'Joe Tester', 26, '20.000');

You can manipulate these objects by accessing some of their properties as follows:

JavaScript
alert(p.name);
alert(pm.salary);

License

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


Written By
Cyberminds Ltd
United Kingdom United Kingdom
I am a senior software Consultant and have been working in IT for the past 6 years.
I started as a junior web developer back in 2006 then was promoted to a full developer a year later then a senior developer some years later.
I have held positions as Scrum Master and I am currently working as a software consultant.
Throughout my experience as a web developer, I have spent a lot of time doing both front and back end development.
I have got experience in the following technologies:
ASP.Net 2+, C#, SQL Server 2005+, Java, SilverLight

As far as front-end development is concerned, I am experienced in CSS, JavaScript, XHTML etc...

Comments and Discussions

 
GeneralMy vote of 3 Pin
Ayan Sengupta19-May-12 1:32
Ayan Sengupta19-May-12 1:32 
QuestionWhy have an inheitance function? Pin
jsc423-Jan-12 0:23
professionaljsc423-Jan-12 0:23 
AnswerRe: Why have an inheitance function? Pin
Joe BTrez11-Jan-12 6:33
Joe BTrez11-Jan-12 6:33 
GeneralMy vote of 4 Pin
Vinod Satapara26-Dec-11 20:16
Vinod Satapara26-Dec-11 20:16 
SuggestionSemicolons Pin
AspDotNetDev23-Dec-11 6:41
protectorAspDotNetDev23-Dec-11 6:41 
GeneralRe: Semicolons Pin
Joe BTrez25-Dec-11 23:28
Joe BTrez25-Dec-11 23:28 

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.