Abstract Methods and Polymorphism in Javascript.

JavaScript doesn’t allow abstract methods. If you are developing JavaScript in an object-oriented style, you need to be aware of what methods your object should or should not have.

Inheritance allows for polymorphism, and achieving polymorphism is further enhanced by using abstract methods.

In Java :

Without declaring the makeSound() method as abstract, and implementing it instead at the super level, you will get some default sound instead from your feathered creation. The usefulness of abstract methods is that it forces the developer to implement some kind of behavior on a particular class they are implementing. Just simply implementing that method at the super level might not make sense. What sounds does a bird make? How long is a piece of string?

Removing the makeSound() method from the super class won’t allow you to use the method makeSound() polymorphically (in most standard OO languages). However in a dynamic language like JavaScript this is considered no problem. You can try calling any kind of method. But during runtime, if you call a method and it ain’t there, well you get :

Thats what duck-typing gives you. To make JavaScript more robust and to ‘fake’ abstract methods in the language I’ve had to turn to a pretty crude method : popping up alerts in empty methods defined in the super object.

A real world example :

In the Page object I have created a two methods which I want all derived objects to include. The Page object supplies HTML elements that frames a page object, eg header elements at the top, and maybe you could have footer elements defined as well.

Implementation :

The implemented TimeSheetPage object needs to implement these methods or an alert message will pop up. This is nowhere near as good as a compile time error, but its unfortunately that best JavaScript can do.

I hope this helps. It has eased some of the pain of JavaScript developement for me. Its a shame Mozilla hasn’t built in a more elegant OO system for Javascript.

Posted in JavaScript | Tagged , , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">