Writing Object-Oriented JavaScript Part 2


Part 1 of this series discussed the object-oriented features of JavaScript. What is unusual about JavaScript is its support of prototype inheritance and the inelegant way that class inheritance is achieved through prototype inheritance.

This installment introduces a framework that applies prototype inheritance in a manner that simplifies writing class hierarchies in JavaScript. Using this framework we can now easily define and derive new classes using a class inheritance pattern very similar to conventional object-oriented languages.

The Strategy

Assigning Base Class Prototypes To Derived Class

To support class inheritance we need to construct a mechanism similar to a virtual function table (vtable). Vtables are simulated by the framework through JavaScript’s prototypes. Prototypes are essentially associative arrays that describe a template of properties assigned to instances. Thus in JavaScript “class inheritance”is simulated by assigning to the prototypes of a derived class the prototype values from its base class. Once assigned, the derived class can either override its prototype entries with its own implementation or default to the implementation supplied to its prototype from the base class.

JavaScript Class Framework (Cfx)

The JavaScript class framework (Cfx) simplifies writing class hierarchies in JavaScript through a well-defined coding pattern. The framework performs class inheritance by automatically assigning the base class prototype and properties to its derived classes.

Cfx is composed of a set of JavaScript objects offering services that define new classes, provide useful DOM routines and JavaScript utilities. These objects are encapsulated by the Cfx object serving as the overall namespace for the framework.

Figure 1. The JavaScript Class Framework (Cfx)


The Cfx.Js (JavaScript) object is a general utility object encapsulating functions identifying object types. It also has functions that extract the string name of an object or function and convert object types to function types.




Figure 2. Cfx.Js methods


Cfx.Class provides the JavaScript class inheritance infrastructure. New classes are defined using Cfx.Class.New method. This method assigns the prototype entries from base classes into the prototype array of the derived class and permits the derived class prototype array to be inherited from multiple base classes in reverse order of its argument list specification. Therefore the class name positioned directly after the derived class in the argument list represents the most significant base class, and is merely a quick-and-dirty way of resolving inheritance conflicts.

Figure 3. Cfx.Class methods


Cfx.Dom encapsulates the Document Object Model providing useful methods for retrieving document items.








Figure 4. Dom object property and methods

JavaScript Intrinsic Objects Extensions

In JavaScript all objects are extensible and Cfx makes full use of this feature. The framework extends the Function object providing the ability to add methods to a class. Object is extende with the className and baseClass properties. These properties are used by Cfx to determine the class hierarchy for all instantiated objects with Object as the base class for all objects.

The Error, Date, and String intrinsic objects are extended with the className and baseClass properties defaulting to Object as thier base class.

Figure 5. JavaScript Intrinsic Extensions in Cfx

For brevity, Error, Date, RegExp, and String default properties and functions are not depicted, only their extensions are depicted. In addition, Cfx extends the String class with the trim function to remove leading and trailing whitespaces from strings. More information about JavaScript intrinsic object extensions is provided below:


Root of all JavaScript objects.


Object representation of a function.


Exception object


Date and time object.


Regular Expression object.


String object.

Developing A Class Hierarchy With Cfx

Using Cfx, we define a class hierarchy and derived classes refining the behavior of their base classes. For example, validating text input elements is very common occurrence and why ASP.NET provides validators. However a situation may arise where you need to write your own client-side validation code for perhaps a specialized requirement. This section demonstrates how you can define a class hierarchy of validators using Cfx.

The following class diagram shows a class hierarchy of validators. The Validator class represents the base class for all derived validators. The TextValidator is derived from the Validator class and the WildcardValidator class is derived from the TextValidator class.

Figure 7. Validator class hierarchy

Writing A Class

The first class of interest is the Validator class. Itrepresents the base class for all validator types. We can think of it as anabstract class although JavaScript does not possess the concept of an abstractclass. Functions in JavaScript serves as both the object’s constructor functionand its class definition.

Using the following code pattern in the constructor function classes are defined in the following three subsections:

  1. Class definition section
  2. Class instance section
  3. Method definition section

Class Definition Section

Class definition and initialization occurs in this block of the constructorfunction. Cfx.Class.IsDefined determines whether theValidator class (actually a JavaScript function object) has beendefined. If the class is not defined, Cfx.Class.New is called tocreate the Validator class. During class initialization,Cfx.Class.New calls back the constructor function, detected byCfx.Class.IsInitializing, to assign methods and properties to thenew class. Do not omit the return statement from theCfx.Class.IsInitializing code block. Control must return back toCfx.Class.New to complete class construction.

Figure 8. Validator class definition section

Class Instance Section

In this section of the Validator class constructor, there is noneed to initialize any instances since the class is not intended forinstantiation. This is how we designate that a class is abstract. In this casethe class instance is merely returned.

Figure 9. Validator class instance section

Method Definition Section

The method definition section defines all the methods whose references areassigned to the class in the class definition section. The class methods aredefined within the constructor function and are scoped to the class. This avoidsexposing the method names to the global namespace preventing name collisions.

Figure 10. Validator method definition section

Deriving classes

TThe TextValidator class is derived using the same coding pattern(class definition, class instance, and method definition section) as theValidator class. In its class definition section,Cfx.Class.New creates the TextValidator classinheriting the class methods and properties defined on theValidator class. The TextValidator adds an accessormethod AcceptChars used to get and set its acceptCharsproperty.

Unlike the Validator class, notice there is addition code in theclass instance section. This is because the TextValidator class isintended for instantiation. The InitInstance method initializesinstances from its class object providing default values. Thus in the code shownbelow, instances of the TextValidator class obtain thefieldName, element, and acceptCharsproperties and their default values from the TextValidator classobject.

>Following the call to InitInstance the constructor arguments areinspected. If there are arguments they are used to override the default valuesof the new instance. The last step is to return the instance from theconstructor.

TThe method definition section of the TextValidator class definesthe AcceptChars accessor method. All other methods and propertiesof the TextValidator class are inherited from theValidator class. Below is the complete definition of theTextValidator class.

Figure 11. TextValidator class definition

Similarly WildcardValidator is derived from TextValidator, adding additional methods and properties.

Figure 12. WildcardValidator class definition


The Inheritance demo program, is an ASP.NET application usingCfx to build a JavaScript class hierarchy. The validators aredefined as wrappers of the text input elements displayed on the sample web page.Using the validator objects we can access and modify the text input elements anddemonstrate class inheritance of the validators.

The URL for this site is http://localhost/JsOOP/Inheritance/WebForm1.aspx.Copy the source code into the JsOOP/Inheritance subdirectory ofyour http://localhost home directory. You can use Visual Studio to create theASP.NET project or use the IIS management tool found in Administrative Tools ofthe Control Panel. This demo has been tested on both version 1.0 and 1.1 of theruntime.

The JavaScript class framework script file is included near the start of theweb page in WebForm1.aspx followed by the script files of thevalidation class hierarchy.

In the OnLoad function validation objects corresponding to thetext elements are created. A WildcardValidator class object wrapsTextBox1 field and it is during this initial object creation thatthe framework creates the entire Validator class hierarchy. Thecall to the InstanceOf method from the valText1 objectdemonstrates the creation of the class hierarchy by the framework.

Objects of the TextValidator class wrap TextBox2and TextBox3 text elements. The following code demonstrates usingthe methods defined by the class hierarchy to manipulate the text elements.Observe how textbox3 is assigned the value of textBox2through the TextValidator objects valText2 andvalText3.


Using Cfx, client-side scripts can now be written using afamiliar object-oriented design and style. While the objects presented here aremerely wrappers for text fields, they do an excellent job of encapsulating andhiding implementation details. This can be very useful for hiding nuances amongthe various browsers rendering your web pages, and most importantly enable codereuse. Structuring your scripts this way also provides you the ability to designricher client-side web pages enhancing the user experience of your web sites.Also note that the naming conventions used in Cfx are pascal casingfor method names and camel casing for property names. This helps to visuallydistinguish between the two.

The final installment demonstrates how you can use this framework to developa class hierarchy of JavaScript control providing rich client-side functionalityfor ASP.NET web pages.controls.

Resource: Codeproject

Leave a Reply

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