XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.

advertisement

Object-oriented JavaScript
by Greg Brown | Pages: 1, 2, 3

Polymorphism

Polymorphism refers to the ability of a caller to invoke a particular method or set of methods on an object without regard to the object's type. For example, we might want to add a speak() method to our Pet class, to allow our Pets to answer the phone when we are not at home; the caller on the other end of the line will not necessarily know or care which Pet is answering the phone, as long as it is able to speak():

In C#:

// C# Pet class

public class Pet
{
    // ...

    public virtual void Speak()
    {
        System.Console.WriteLine(GetName() + " says...");
    }
}

// C# Dog class

public class Dog : Pet
{
    // ...

    public override void Speak()
    {
        base.Speak();
        System.Console.WriteLine("woof");
    }
}

// C# Cat class

public class Cat : Pet
{
    // ...

    public override void Speak()
    {
        base.Speak();
        System.Console.WriteLine("meow");
    }
}

In JavaScript:

// JavaScript Pet class
// ...

Pet.prototype.speak = function() {
    alert(this.getName() + " says...");
}


// JavaScript Dog class
// ...

Dog.prototype.speak = function() {
    Pet.prototype.speak.call(this);
    alert("woof");
}


// JavaScript Cat class
// ...

Cat.prototype.speak = function() {
    Pet.prototype.speak.call(this);
    alert("meow");
}

Note that the same call() function used to invoke the base class constructor functions is also used to invoke method on the base class:

Pet.prototype.speak.call(this);

In this case, however, the target function name is the fully qualified name of the base class method, Pet.prototype.speak.

Invoking the methods is the same as before:

C#:

p = new Dog("Max");
p.Speak();

p = new Cat("Fluffy");
p.Speak();

JavaScript:

p = new Dog("Max");
p.speak();

p = new Cat("Fluffy");
p.speak();

The output of this program should be the following (see Figures 3-6):

Figure 3
Figure 3. Output is "Max says..."

Figure 4
Figure 4. Output is "woof"

Figure 5
Figure 5. Output is "Fluffy says..."

Figure 6
Figure 6. Output is "meow"

Although it may not offer features as powerful as C# or Java, JavaScript is more capable than many web developers may know, and it can be used to provide the structure of object-oriented development to the growing number of AJAX applications currently being deployed on the web.



1 to 4 of 4
  1. Great help
    2009-11-08 21:59:50 Abhijit Roychoudhury
  2. Good and basic article
    2008-05-30 10:46:26 Atul Jindal
  3. Douglas Crockford would disagree
    2006-06-08 06:27:20 joshua.gitlin@gmail.com
  4. Nice articles, but a major imprecision
    2006-06-08 00:17:16 andrea.campi
1 to 4 of 4