Click here to Skip to main content
6,629,377 members and growing! (20,911 online)
Email Password   helpLost your password?
Web Development » Client side scripting » General     Beginner License: The BSD License

Exploring OOPS - JavaScript Style: Part 3 - Polymorphism

By mastergaurav

This article, 3rd Part in the series of 3-articles, discusses Polymorphism in JavaScript
Javascript, Architect, Dev, Design
Posted:19 Jun 2008
Updated:2 Aug 2008
Views:8,403
Bookmarked:7 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
6 votes for this article.
Popularity: 2.25 Rating: 2.89 out of 5
1 vote, 16.7%
1
2 votes, 33.3%
2

3

4
3 votes, 50.0%
5

Introduction

In the third and last article of the series of "Exploring OOPS - JavaScript Style", we look at polymorphism in JavaScript.

Note: This article is an adaption (may be a mirror) of the article originally posted at Edujini™ Eduzine™ here.

All the three articles of the series:

Polymorphism literally means "multiple forms". In OOAD, it means that an object reference can take different behave differently depending upon the scenario.

Technically, there are two types of polymorphism - compile-time polymorphism and runtime polymorphism. One of the ways to implement compile-time polymorphism is method overloading while runtime polymorphism can be implemented by method overriding.

Downloads

The downloads are available in the Downloads area.

Compile-time Polymorphism

All functions in JavaScript are overloaded by default. Surprised, isn't it? Let's take a simple code below for analysis:

<html>
  <head>
    <title>OOPS in JavaScript - Polymorphism</code>
    <script language="'javascript'" type='text/javascript'>
      /**
       * (C) 2008, Gaurav Vaish, Edujini Labs Pvt Ltd
       * http://www.mastergaurav.com
       * http://eduzine.edujini-labs.com
       */

      function addMethod(x, y)
      {
        document.writeln('x: ' + x + ', y: ' + y);
      }
    </script>
  </head>
  <body>
  <pre><script language="'javascript'" type='text/javascript'>
      addMethod();
      addMethod(1);
      addMethod(1, 2);
      addMethod(1, 2, 3);
      addMethod(1, 2, 3, 4);
    </script>
  </pre>
  </body>
</html>

For the time being, do not worry about the actual results. What is more important is that invocation of these methods do not result in any error whatsoever! And that's because all methods in JavaScript are, by default, overloaded. And did somebody say - that's compile-time polymorphism?

What we provide in the parameter-list to a JavaScript function is just names to those parameters so that it is convenient to access them. All parameters passed to a function are available through an automatically-created local-variable arguments. Let's redefine the same method to access all parameters passed to it, convert each into number and return the their sum (if they are not NaN).

<html>
  <head>
    <title>OOPS in JavaScript - Polymorphism</code>
    <script language="'javascript'" type='text/javascript'>
      /**
       * (C) 2008, Gaurav Vaish, Edujini Labs Pvt Ltd
       * http://www.mastergaurav.com
       * http://eduzine.edujini-labs.com
       */

      function addMethod(x, y)
      {
        var rv = 0;
        var length = arguments.length;
        var n;

        for(var i = 0; i < length; i++)
        {
          n = Number(arguments[i]);
          if(!isNaN(n))
          {
            rv += n;
          }
        }
        return rv;
      }
    </script>
  </head>
  <body>
  <pre><script language="'javascript'" type='text/javascript'>
      document.writeln(addMethod());
      document.writeln(addMethod(1));
      document.writeln(addMethod(1, 2));
      document.writeln(addMethod(1, 2, 3));
      document.writeln(addMethod(1, 2, 3, 4));
    </script>
  </pre>
  </body>
</html>

arguments if of the type Arguments. Apart from other properties, one critical thing to which it provides access to is all the parameters passed to the function while invoking it.

Though it may sound unusual for those who are used to working with languages like C, C++, Java, C# etc but probably they can relate this to varargs. And the same mechanism is available for instance methods (for custom types) as well.

Runtime Polymorphism

Method overriding? Haven't we already discussed this in the previous article while discussing about inheritance?

Summary

In this article we learnt about polymorphism in JavaScript.

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

mastergaurav


Member
Gaurav lives in Bangalore, the Silicon Valley of India.
He is the Chief Technology Officer at Edujini Labs Pvt Ltd - a company that pioneers in Technology Trainings, Education using Technology and Technical Consultancy.
www.edujini-labs.com

His technical strength lies in having deep understanding of not one or two but dozens of enterprise frameworks.

Today, he is an independent guy:
- He is a programming language independent guy, well almost. He is proficient in C, C++, Java, C#, VB.Net, C++.Net, JavaScript, PHP, Tcl, Python, Ruby
- He is an OS independent guy, well almost. Has worked and developed at length on HP-UX, Linux (Redhat / Mandrake), Macintosh (9, 10.x), Windows (NT, 2000, 2003, XP, Vista), Solaris (8, 9, 10)
- He is a target independent guy, well almost. Has worked on thick clients (mainly desktops) as well as thin clients (mainly alternative platforms - Symbian, PalmOS, WinCE, WinXP Embedded, Linux Embedded)

Today, his thrust areas are Service Oriented Architecture (implementation expert in Java, .Net and PHP; integration with Mainframe and other legacy environments), Mobile Technologies and RFID.

His domain expertise include e-Learning, Anti-Piracy and Telecommunications.

Before co-founding Edujini™, he has worked in the capacity of Head, R&D at TeN, India and as Member, Technical Staff in R&D Team at Adobe Systems, India.

He holds a Bachelor's Degree (B. Tech.) from IIT Kanpur www.iitk.ac.in. His major was in EE with specialization in DSP (SSP).

His hobby is listening music, reading books (no, he can't read novels), photography and travelling.

Should you wish to talk to him, you can drop him a mail at gaurav[dot]vaish[at]gmail[dot]com. He generally responds within 24-48 hrs unless there is a compelling reason.

And yeah... here's his personal website:
http://www.mastergaurav.com

Smile
Occupation: Web Developer
Location: India India

Other popular Client side scripting articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
Generalnice article. PinmemberRajib Ahmed18:03 19 Jun '08  
GeneralRe: nice article. Pinmembermastergaurav5:00 20 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Aug 2008
Editor:
Copyright 2008 by mastergaurav
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project