Implementing "Real" Classes in JavaScript, Page 2
The Platform Implementation
While the complete documented version of the platform. is contained in a few JavaScript include files, the compact, standalone code in Listing 3 implements the basic technique. Lines 12-18 implement the "super" capability. Lines 27-31 replace the original class function with a wrapper function that, in turn, uses the original class as its prototype. Instances of the wrapper class will hold all the instance variables and only the singleton prototype objects contain method definitions.
Listing 3. The GrvObject technique's basic implementation (grvObject.js)
1 Class(GrvObject); //special root class
2 function GrvObject(){
3 this.souper = function() {
4 var superMethod = this.souper.caller.souper;
5 return (superMethod) ? superMethod.apply( this, arguments ) : null;
6 }
7 }
8
9 function grvExtends( superClass ){ //link super and sub classes
10 this.baseClass.prototype = (this==GrvObject) ? null : superClass.prototype;
11 this.prototype = new this.baseClass();
12 if (this.baseClass.prototype)
13 for (var x in this.prototype) { // iterate over all properties
14 var m = this .prototype[x]; // the method
15 var s = this.baseClass.prototype[x]; // its super
16 if (s && (s!=m) && (m instanceof Function) && (s instanceof Function))
17 m.souper = s;
18 }
19 }
20
21 function grvFuncName(f){ //extract name from function source
22 var s = f.toString().match(/function\s*(\S*)\s*\(/)[1];
23 return s ? s : "anonymous";
24 }
25
26 function Class( theClass ){
27 var originalClass = theClass;
28 self[ grvFuncName(theClass) ] = theClass = function(){
29 arguments.callee.prototype.konstructor.apply( this, arguments );
30 }
31 theClass.baseClass = originalClass;
32 theClass.Extends = grvExtends;//so we can call Extends as a method
33 theClass.Extends(GrvObject);//required here even if overridden later
34 return theClass;
35 }
The utility function grvFuncName (lines 21-24) takes a function object and returns the function name (made possible because, in JavaScript, the function object contains the function source code).
Conclusion
With the presented compact implementation. JavaScript developers can take advantage of most of the features of Java classes, thus enabling the use of robust design patterns needed for AJAX and RIA applications. Use of this technique does not preclude mixing in other techniques or legacy code thus allowing the technique to be added to existing code.
Examples
The source code in this article is available for viewing or download at Polyglotinc.com or here at Developer.com.
About the Author
As principal consultant of PolyGlot, Inc., Bruce Wallace has provided consulting and custom computer software development services around the world. Projects have been completed in Sydney Australia, Perth West Australia, "Silicon Valley", "Route 128" MA, Austin TX, Atlanta GA, and Charlotte NC.
Copyright
© Copyright, 2006-2007, PolyGlot, Inc.
