HTML and CSS Reference
In-Depth Information
Listing 7.38 Implementing Sphere with inherit2
function Sphere(radius) {, radius);
Sphere.inherit2(Circle, {
area: function () {
return 4 * this._super();
}); Performance of the super Method
Using the inherit2 method we can create constructors and objects that
come pretty close to emulating classical inheritance. It does not, however, per-
form particularly well. By redefining all the methods and wrapping them in
closures, inherit2 will not only be slower than inherit when extend-
this. _ super()
this. _ as well.
Further hits to performance are gained by the try-catch, which is used to ensure
that this. _ super is restored after the method has executed. As if that wasn't
enough, the method approach only allows static inheritance. Adding new methods
to Circle.prototype will not automatically expose _ super in same named
methods on Sphere.prototype . To get that working we would have to imple-
ment some kind of helper function to add methods that would add the enclosing
function that sets up _ super . In any case, the result would be less than elegant and
would introduce a possibly significant performance overhead.
I hope you never use this function; JavaScript has better patterns in store. If
anything, I think the _ super implementation is a testament to JavaScript's flexi-
bility. JavaScript doesn't have classes, but it gives you the tools you need to build
them, should you need to do so. A _ super Helper Function
A somewhat saner implementation, although not as concise, can be achieved by
implementing _ super as a helper function piggybacking the prototype link, as
seen in Listing 7.39.
Search WWH ::

Custom Search