Wednesday, August 13, 2008

Invoking Overridden Methods in Javascript

When a subclass defines a method that has the same name as a method in the superclass, the subclass overrides that method. This is a relatively common thing to do when creating subclasses of existing classes. Anytime you define a toString( ) method for a class, you override the toString( ) method of Object, for example.

A method that overrides another often wants to augment the functionality of the overridden method instead of replacing it altogether. To do that, a method must be able to invoke the method that it overrides. Invoking an overridden method is more awkward than invoking a superclass constructor, however.

Let's consider an example. Suppose the Rectangle class had defined a toString( ) method (as it should have in the first place):

Rectangle.prototype.toString = function( ) {
    return "[" + this.width + "," + this.height + "]";

PositionedRectangle is a simple enough class that its toString( ) method can just return the values of all properties. But for the sake of example, let's handle the position properties and delegate to its superclass for the width and height properties. Here is what the code might look like:

PositionedRectangle.prototype.toString = function( ) {
    return "(" + this.x + "," + this.y + ") " + // our fields
Rectangle.prototype.toString.apply(this); // chain to superclass

The superclass's implementation of toString( ) is a property of the superclass's prototype object. Note that you can't invoke it directly. Invoke it with apply( ) so that you can specify the object on which it should be called.

1 comment:

Anonymous said...

What a great web log. I spend hours on the net reading blogs, about tons of various subjects. I have to first of all give praise to whoever created your theme and second of all to you for writing what i can only describe as an fabulous article. I honestly believe there is a skill to writing articles that only very few posses and honestly you got it. The combining of demonstrative and upper-class content is by all odds super rare with the astronomic amount of blogs on the cyberspace.

Subscribe in a Reader