Professional websites at affordable prices.

 +44(0)2033686958
Professional Websites at Affordable Prices - Cyberminds Ltd

BLOG ARTICLE

JavaScript

Polymorphism in JavaScript

Monday, 16 January 2012 06:16 by Joseph Bolla Software Consultant

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

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.

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) {
            debugger;
            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());
        }

 

Brilliant article. Well Done!

Jeff Wonder   18/11/2012 22:18:00

this script works incorrect, you should check check it before publish, method "get_age" in arrPeople[1] doesn't work you just erase him by Manager.prototype = { wake_up: function () { alert('I am in control'); } }

Konstantin   26/11/2012 14:49:18

this script works incorrect, you should check check it before publish, method "get_age" in arrPeople[1] doesn't work you just erase him by Manager.prototype = { wake_up: function () { alert('I am in control'); } }

Konstantin   26/11/2012 14:49:34

this script works incorrect, you should check check it before publish, method "get_age" in arrPeople[1] doesn't work you just erase him by Manager.prototype = { wake_up: function () { alert('I am in control'); } }

Konstantin   26/11/2012 14:59:40

An extra thing. In my opinion that there are lots of travel insurance online pages of reputable companies than enable you to enter your holiday details and have you the quotes. You can also purchase the actual international travel insurance policy on the internet by using your credit card. All that you must do will be to enter your existing travel specifics and it is possible to see that the plans side-by-side. Only get a hold of that the package that suits your capacity to pay and needs after which use your bank credit card to buy that the idea. Travel insurance on that the web is mostly a fine method to start looking for a respectable business to lookup out international travel cover. Thanks for expressing your ideas.

Kennedy   03/12/2012 03:07:15

Awesome issues here. I am very happy to see your post. Thanks so much and I'm having a look ahead to contact you. Will you please drop me a e-mail?

Busby   13/01/2013 13:16:06

I like what you guys tend to be up too. Succh clever work and coverage! Keep up the very good works guys I've included you guys to blogroll.

Adrian Marquis   09/10/2014 00:03:37

It's hard to find experienced people for this topic, however, you sound like you know what you're talking about! Thanks

Remona Knudsen   09/10/2014 22:29:21

Permit this message and we will help save an made up critter!

Elaine Pettway   14/10/2014 22:08:24

I like the valuable information yoou provide in your articles. I'll bookmark your blog and check again here regularly. I am quite certain I'll learn a lot of new stuff right here! Best of luck foor the next!

Heath Laufer   07/11/2014 22:38:45

Hi to all, how is everything, I think evrry one is getting more from this web site, and your views are nice for new viewers.

Elizabet Jonson   25/11/2014 12:05:04

I'm very pleased to find this website. I want to to thank yyou for youjr time for this particularly wonderful read!! I definitely liked every part oof it and i also have you book-marked to look at new things in your web site.

Lila McGuire   14/12/2014 00:16:53

Hello there! This blog pot coupd not be written anyy better! Loking through this post reminds mee of my previous roommate! He always kept talking about this. I will forward this information tto him. Fairly certain he will have a great read. Many tuanks for sharing!

Eve Hyett   17/12/2014 13:33:33

It's difficult to find well-informed people about this topic, but you sound like you know what you're talking about! Thanks

Adriene Brace   18/12/2014 16:52:12

Here's a list off a couple of different ways to view things: . The information contained in tthis guid is easy to follow and provids you with a program that will assist you in bith losing body fat and also gaining lean muscle mass. You will love swimming because it's easy on your body and good for the heart but it will do little to help you lose fat.

Elwood Fabian   19/12/2014 17:30:43

Great article! We aare linking to this particularly great content on our site. Keep up the good writing.

Alba Maguire   21/12/2014 14:29:09

Use this form to leave a comment.

 
 
 
Security Code Enter code as it appears in the box below
Security Code  
   
                       

Cookies | Blog | Contact | Terms & Conditions | Links | Sitemap