Tuesday, August 15th, 2006
I set out to see if I could devise a working design of my own. It took me about a week to work out something that behaved correctly under all situations, but once I felt confident that it was working, I quickly integrated the approach into the framework. As it stands now, both the beta and beta2 releases of ThinWire leverage that initial design.
His analysis starts with standard prototype chaining techniques (SubClass.prototype = new BaseClass();) and explains where they fall down, in particular problems with calling superclass methods. He then walks through a range of improvements, notably Doug Crockford’s well-known “classic inheritance” technique.
… (I)t should be clear that the results of the above example are incorrect. Additionally, a downside of Crockford’s approach and of many other approaches, is that every super call requires an additional method call and additional processing of some kind. Whether this is an issue for your situation, will depend on how many super calls you have in your code. ThinWire makes extensive use of super calling in it’s client-side code and therefore it’s important that super calls are as fast as possible.
Josh eventually developed an alternative solution that is somewhat Aspect-Oriented:
Essentially, ‘extend’ wraps every method in your class definition with an intermediate function that swaps the super class reference ‘$’ to the correct reference with every method call. The only real issue with this approach is that it requires a number of intermediate functions, which may have an impact on performance.
A further refinement exploits the little-known callee property.
(T)he ‘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.
(Thanks to Ted Howard for the link.)
Posted by Michael Mahemoff at 6:05 pm