BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Towards the Optimal Javascript Inheritance Technique

Towards the Optimal Javascript Inheritance Technique

Lead developer of the ThinWire Framework Joshua Gertzen has written an article going over existing approaches to implementing OO inheritance in Javascript and explains the final solution that they needed on the Thinwire framework for super class method calling.  The Thinwire framework is Java product for building RIA style Ajax frameworks in pure Java.  Unlike Google GWT, ThinWire doesn't compile Java code into Javascript, instead Java code is executed on the server like the ZK framework.   Thinwire is targetted at business application developers and attempts to provide a complete RIA solution that that hides all javascript, css, and even html.

Joshua reviewed existing "ugly" prototype approachs such as simple inheritance without super calls,  broken attempts at adding super class calling, hard coded super calling, Douglas Crockford's strategy proposed in "Classical Inheritance in JavaScript" (which he found broken and also slow), and finally, a dynamic super calling approach which is fast and works.
This final design leverages a little known feature in JavaScript, although one that is supported by all major browsers. During the execution of any function, you can refer to the arguments that were passed in via the 'arguments' array. That's fairly well known, but the lesser known detail is that the 'arguments' array contains a reference in the property 'callee', which points to the current function that is being executed. This is important, because it's the only way that you can get such a reference since the function reference available via the 'this' object, always refers to the overridden function that is defined in the class at the top of the hierarchy.
Earlier this year, Dean Edwards published specialized base class for doing OO in Javascript that also addresses these problems and is being considered for inclusion in 2.x versions of the popular Prototype Javascript framework.

Rate this Article

Adoption
Style

BT