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

Hi, I do believe this is a great site. I stumblerdupon it ;) I may return yet again since i have saved as a favorite it. Money and freedom is the greatest way to change, mmay you be rich and continue to guide others.

Andreas Glassey   23/12/2014 18:22:27

Please let me kknow if you're looking for a author for your site. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I'd really like to write some articles for your blog in exchange for a link back to mine. Please send me ann e-mail if interested. Regards!

Thurman Yoo   24/12/2014 20:35:56

Please let me kknow if you're looking for a author for your site. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I'd really like to write some articles for your blog in exchange for a link back to mine. Please send me ann e-mail if interested. Regards!

Thurman Yoo   24/12/2014 20:35:56

I'm not sure exactly why but this weblog is loading very slow for me. Is anyone else having this problem or is it a issue on my end? I'll check back later and see if the problem still exists.

Leoma Dubois   02/01/2015 02:14:21

We really are passing along free product samples of premium Belgium chocolates. To become allowed, simply just answer our comment along with your address and we'll send it out over the next business day.

Cole Mullagh   04/01/2015 17:37:24

Appreciate the recommendation. Will try it out.

Jeremiah Venuti   08/01/2015 04:18:48

Now obviously some people start losing their hair because they are taking certain medications, having cancer treatment, or have developed some sort of disease that causes hairloss. This is the best way to be sure of finding an effective treatment that works for you. This is generally hereditary and is caused by the hormone testosterone going through a kind of metamorphosis into this new hybrid hormone they have named DHT.

Melina Rymer   10/01/2015 00:15:01

You have a few minutes (30 max) prior to having to turn up for the saliva driving test.

Mckinley Kellermann   10/01/2015 13:18:20

When someone writes an aragraph he/she retains thee idea of a user in his/her mind that how a user can bee aware of it. So that's why this paragraph is perfect. Thanks!

Natalia Ogilvy   10/01/2015 22:19:47

Piece of writing writing is also a excitement, if you be familiar wjth after that yoou ccan write oor else it is complicated to write.

Lovie Perkins   12/01/2015 18:18:53

I was recommended this blog by way of my cousin. I am now not positive whether or nnot this submjit is written through him as no one else know such designated approximatepy my trouble. You are amazing! Thank you!

Kathlene Hanley   14/01/2015 02:29:23

I usually do noot drop a bunch of comments, however after reading some of the comments on Polymorphism in JavaScript. I actuaply do have 2 questions for yyou if you don't mind. Is it just me or does it look as if like some of the responses look as if they are written by brain dead individuals? :-P And, if you are writing on additional online social sites, I woulkd like tto keep up with you. Would you list of all of all your social community sites like your linkedin profile, Facebook page or twitter feed?

Boyd Baskerville   16/01/2015 23:27:27

Does your blog have a contact page? I'm having problems locating it but, I'd llike to send you an email. I've got some creative ideas for your blog you might be interested in hearing. Either way, great website andd I llook forward to seeing iit improve over time.

Conrad Cowen   20/01/2015 22:58:23

If you want to grow your know-how only keep visiting this web site and be updated wwith the newest news update posted here.

Justina Dehaven   23/01/2015 12:36:52

An outstanding share! I've just forwarded this onto a colleague whoo had been doing a little research on this. And he in fact ordered me lunch due to the fact that I found it for him... lol. So let me reword this.... Thank YOU for the meal!! But yeah, thanx for spending time to talk about this topic here on your web site.

Torri Cornett   24/01/2015 22:46:38

Prove your bandwidth, easy and free utilizing TestInternetSpeed.Link. It is precise, fast and works fine on Android, iPhone, Tablets, and aall computers with an updated web navigator. Initially a ping test is done and the faster server is selected, to make all the internet soeed tests.

Reyes O'Donnell   27/01/2015 01:50:30

You have to invest in comfy seating to make your media room inviting. Include a refrigerator for drinks and a microwave for instant popcorn. That is hard to say but one major factor that dictates the size of your master bathroom will be what size is the space you have to work with.

Annabelle Kwan   04/02/2015 08:57:17

It's very simple to find out any topic on net as compared to textbooks, as I found this article at this site.

Florida Monds   06/02/2015 21:32:19

Howdy! Would you mind if I share your blog with my myspace group? There's a lot of folks that I think would really appreciate your content. Please let mme know. Thanks

Suzanne Bellew   14/02/2015 12:55:20

Very great post. I simply stumbled upon your weblog and wanted to mentio that I've trulky ehjoyed browsing your weblog posts. In any case I will be subscribing in your rss feed and I'm hoping you write once more very soon!

Leona Enderby   16/02/2015 00:46:58

My coder is trying to convince me too move to .net from PHP. I have always disliked thhe idea because off thee costs. But he's tryiong none the less. I've bwen using Movable-type on numerous websites for about a year annd am anious about switchng tto another platform. I have heard fantastic things about blogengine.net. Is there a way I can import all mmy wordpress content into it? Any kind of help would be greatlky appreciated!

Kathrin Menge   21/02/2015 14:44:42

Everything said made a great deal of sense. However, think on this, what iif you were to create a killer title? I ain't suggesting your content is nnot solid, however what if you added a title that grabbed people's attention? I mean Polymorphism in JavaScript iss a little boring. You might look at Yahoo's front page and watch how they create news titles to grab people interested. You might add a related video or a picture or two to get people excited abouit everything've written. Just myy opinion, it would make your posts a little livelier.

Estelle Kalb   24/02/2015 04:29:35

Pretty! This was an extremely wonderful article. Thank you for supplying these details.

Rodger McNish   26/03/2015 04:33:07

I believe that is among the such a lot important information for me. And i'm satisfied reading your article. However wanna commentary on few common things, The website style is wonderful, the articles is actually great : D. Good job, cheers

Vivien Beliveau   29/03/2015 20:46:08

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