Object Oriented Javascript - Part 2 | WebReference

Object Oriented Javascript - Part 2

current pageTo page 2To page 3
[next]

Object Oriented Javascript - Part 2

In the previous article I demonstrated how JavaScript classes could be written to inherit the methods and properties of another class. This technique paves the way for sophisticated JavaScript applications using the benefits of class inheritance and polymorphism.

In this article I will demonstrate some extensions that will allow developers to extend intrinsic JavaScript classes such as String, Date and to a certain extent, Array.

The Problem With Inheriting From Intrinsic Classes

As some readers may have discovered, using the inherit function to inherit from the intrinsic classes won't work. This is an irritation as it's often useful to inherit from these basic classes in order to develop various extensions that have extra behaviours, such as validation of values and specialized formatting.

The reason that the intrinsic classes don't support this inheritance model is that they're not strictly JavaScript classes. Although the intrisic classes do inherit from Object, they are optimized to run efficiently within the Browser's JavaScript engine and don't necessarily behave like scripted classes. Evidence of this can be seen by enumerating the contents of an intrinsic class' prototype:

for ( var i in String.prototype )

{

   alert('String.prototype[' + i + '] = ' + String.prototype[i]);

}

Although results may vary, typically the methods and properties are not included.

It's not just that the methods are not enumerated, their implementations cannot be translated either. Consider the following code:

function MyString(s)

{

   String.call(this,s);

   this.charAt = String.prototype.charAt;

}

This class attempts to construct itself using the JavaScript String constructor and attach the charAt method to use on its supposed string internal value. It's not long before this code runs into some unexpected behaviour. For example:

var s = new MyString("hello");

alert(s.charAt(1));

alert(s.charAt(2));

alert(s.charAt(3));

alert(s.charAt(4));

alert(s.charAt(5));

alert(s.charAt(6));

Running the above code in Internet Explorer results in the letters 'o', 'b', 'j', 'e', 'c' and 't'; which are somewhat different to what might have been hoped for.

 

current pageTo page 2To page 3
[next]

Created: March 27, 2003
Revised: April 28, 2006

URL: http://webreference.com/programming/javascript/gr/column19/1