Click here to Skip to main content
Click here to Skip to main content

Polymorphism in JavaScript

, 16 Jan 2012
Rate this:
Please Sign up or sign in to vote.
How does Polymorphism work in JavaScript.

Introduction

Polymorphism in Object-Oriented Programming is the ability to create a variable, a function, or an object that has more than one form.

Background

The primary usage of Polymorphism in Object-Oriented Programming is the ability of objects belonging to different types to respond to methods, fields, or property calls of the same name, each one according to an appropriate type-specific behaviour.

The programmer does not have to know the exact type of the object in advance, and so the exact behaviour is determined at run-time. This is what we call late binding or dynamic binding (this make Polymorphism a very cool feature). Requirements are such that, there must be properties with the same name and the same parameter sets in all the superclasses, subclasses and interfaces.

Using the code

As far as JavaScript is concerned, we really don’t have interfaces as in other programming languages but we do have superclasses and subclasses. Going back to my article on JavaScript Inheritance, we have created classes that inherit from others.

Let’s reuse the same example, this time we will create a class Person then another class called Manager that inherits from Person. Both classes will include a method called wake_up(). We will then create objects of both types and put them in an array.

When we loop through that array, the system will call the function wake_up() on each of the objects and the implementation will be determined dynamically.

Let’s define our class Person.

  Person = function (id, name, age) {
            this.id = id;
            this.name = name;
            this.age = age;
           // alert('A new person has been accepted');
        }
        /* definition of our Person class */
        Person.prototype = {
            /** wake person up */
            wake_up: function () {
                alert('A person is awake');
            },
            /** retrieve person's age */
            get_age: function () {
                return this.age;
            }
        }

Now let us create an Inheritance class so that other classes can inherit from our class person. For more details and demo on inheritance, refer to my article on JavaScript Inheritance by clicking here.

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; }

Ok we are then going to define our class Manager as follows:

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

Our class Manager will inherit from Person as follows:

Inheritance_Manager.extend(Manager, Person);

Let’s add more functionality and overwrite our wake_up() function

 Manager.prototype = {
    wake_up: function () {
        alert('I am in control with Polymorphism');
    }
 }

Now we create an array and store in objects of type Person and Manager.

var arrPeople = new Array();
arrPeople[0] = new Person(1, 'Joe Tester', 26);
arrPeople[1] = new Manager(1, 'Joe Tester', 26, '20.000');

See how the function wake_up() behaves based on the different objects we have. This is what we call Polymorphism. Polymorphism makes things so simple when you have many objects that present the same interface but different implementations.

for (var i in arrPeople) {
   arrPeople[i].wake_up();
   alert(arrPeople[i].get_age());
}

Many people don’t believe that JavaScript is fully-fledged Object Oriented Programming Language but I think JavaScript just does things its own way which is different from other languages. As we can see in the case of Polymorphism here, there is no difference with other programming languages. So it is fully polymorphic.

Here is the complete code:

     /** This is our Person class */
            Person = function (id, name, age) {
                this.id = id;
                this.name = name;
                this.age = age;
               // alert('A new person has been accepted');
            }
            /* definition of our Person class */
            Person.prototype = {
                /** wake person up */
                wake_up: function () {
                    alert('A person is 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 = {
                wake_up: function () {
                    alert('I am in control');
                }
            }    

            var arrPeople = new Array(); 
            arrPeople[0] = new Person(1, 'Joe Tester', 26);
            arrPeople[1] = new Manager(1, 'Joe Tester', 26, '20.000');    

            for (var i in arrPeople) {
                arrPeople[i].wake_up();
                alert(arrPeople[i].get_age());
            }

License

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

About the Author

Joe BTrez
Other 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

 
QuestionNot able to test the code shared in the article PinmemberMember 105056385-Jan-14 20:42 
AnswerRe: Not able to test the code shared in the article PinmemberJe712-Jun-14 2:44 
Questionthe example isn't "testing" polymorphism but is rather showing inheritance [modified] Pinmemberalklkim29-Nov-12 14:45 
I don't think your code is "testing" polymorphism.
"var arrPeople = new Array();" isn't actually an array of a Person type, it's just a generic array.
 
And the following code would work as well:
var arrPeople = new Array();
arrPeople[0] = new Person(1, 'Joe Tester', 26);
arrPeople[1] = new Manager(1, 'Joe Tester', 26, '20.000');
arrPeople[2] = { wake_up: function() {
                   alert('I am not in control');
                 }
               };
 
for (var i in arrPeople) {
    arrPeople[i].wake_up();
}


modified 29-Nov-12 21:01pm.

QuestionCool PinmemberCIDev14-Feb-12 4:03 
QuestionA cool sample of polymorphism but... Pinmembermarcominas28-Jan-12 3:31 
AnswerRe: A cool sample of polymorphism but... Pinmemberliorafar18-Oct-12 5:30 
QuestionThis is a pretty cool pattern... PinmemberJake Moon24-Jan-12 10:56 
GeneralMy vote of 5 PinmemberCharles17718-Jan-12 9:20 
QuestionHow was this polymorphism? PinmemberDaniel Gidman16-Jan-12 5:12 
AnswerRe: How was this polymorphism? PinmemberJoe BTrez16-Jan-12 5:51 
QuestionRe: How was this polymorphism? PinmemberDaniel Gidman16-Jan-12 10:49 
GeneralMy vote of 5 PinmemberPablo Aliskevicius16-Jan-12 3:31 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140718.1 | Last Updated 16 Jan 2012
Article Copyright 2012 by Joe BTrez
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid