Extending JavaScript Objects in the Classical Inheritance Style

Many authors of JS libraries have made some attempt to emulate familiar Object-Oriented (OO) constructs such as those found in C++ and even more so in Java. The goal is not so much to make JavaScript more Object-oriented, although that is a positive side effect. Rather, it's to make JavaScript objects more palatable to developers who grew up with OO languages. I demonstrated one possible implementation for creating classes in the Create an Object-oriented JavaScript Class Constructor article. Today, I'd like to continue where we left off last time and add some extensibility to the Class constructor function.

The Class Function Revisited

The Class function takes an object literal ("methods") which contains the class's public methods. These are copied to the new class using a technique called method borrowing. Finally, a default constructor is created if there are none defined within the methods object (just as in Java). All classes have code to call their initialize function. These act as the proper OO constructor, not to be confused with the JavaScript object constructor, which encompasses the klass function that contains the call to this.initialize():

Passing the Parent to the Class() Constructor Function

Any way you slice it, the Class() constructor function needs to know who its daddy is. I personally like the simplicity of adding it as an optional first input parameter. The following Employee class template extends Person and adds the id property and anotherFunction() method:

Accommodating the Optional First Input Parameter

An if statement is required to determine the first argument's type. It can be one of two types: if the first argument is the parent class, then the typeof operator will identify it as a function type; otherwise, it would evaluate to an object. If the class has a parent, its methods must be copied over to the child. Notice that extend() must still be called to include methods which are overridden by the child class:

That's Just $super!

In Java, a class can call a parent method using the super keyword. In JavaScript, the super keyword is also reserved for future use, so we can't use it. Instead, I chose to implement it as a method called $super. You would call it from the child class using this.$super(), passing it the name of the method to execute and arguments:

this.$super('initialize', name, age);

The $super is added in the extend() method, so that every class has access to it. I have seen examples where the author sets it in the klass constructor. That falls apart when you have to traverse more than one level as is frequently the case in constructor chaining. The reason is that the constructor is only called when a class is instantiated using the new keyword. The child class's parent doesn't receive it because it is based on the class template, and NOT the instance.

$super() employs a common JavaScript technique for passing method arguments on to another method, calling Array.prototype.slice(). An additional advantage to using slice() is that we can parse out the method argument as well. The Function.apply() method is called on this.$parent[method] so that the parent and arguments can be passed on to the function. The parent must be set as the object on which to apply the parent method as using "this" will cause the function to loop indefinitely!

Copying Method Properties

It is not enough to copy methods from the parent to the child class; properties must also be copied over. This is because the initialization code that creates and sets class properties belongs to the parent that owns the initialize() function.

The ideal place to copy properties is in the klass constructor because it has access to both the property names and their values. A regular expression parses out the parameter list from the function source code. From there, the argument list is split on the commas and iterated over to set each property:

Conclusion

Another approach I considered for accessing properties was to use getter and setter methods rather than allow child classes to access properties directly using the this pointer. Ultimately, the solution you use depends on how available you want to makes your class attributes. Accessing them directly mimics the protected access modifier in Java, while forcing the use of getters and setters treats properties more like private class members.

If you enjoyed this article, please contribute to Rob's less lucrative music career by purchasing one of Rob's cover or original songs from iTunes.com for only 0.99 cents each.

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleConsulting.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you'll receive 15% off for mentioning that you heard about it here!

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His former band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92).