Inheritance using Closures and Prototypes
Early implementations of the Microsoft AJAX library made use of closures-based inheritance, and in the final stage the code was rewritten to use prototypes. In the following few pages we'll quickly discuss both techniques.
Inheritance Using Closures
In classic OOP languages such as C#, C++, or Java, you can extend classes through inheritance. Closure-based inheritance is implemented by creating a member in the derived class that references the base class, and calling that member. This causes the derived class to inherit all the base class members, effectively implementing the concept of inheritance.
To demonstrate this technique, we'll implement two classes:
Car class constructor receives a car name as parameter, and it has a method named
Drive(). The class
SuperCar inherits the functionality of
Car, and adds a new method named
Fly(), reflecting the additional functionality it has in addition to what
Car has to offer. The diagram in Figure 3-6 describes these two classes.
Loading this script in a browser would generate the results shown in Figure 3-7. It can be tested online.
The exercise demonstrates that inheritance really works.
SuperCar only defines the capability to
Fly(), yet it can
Drive() as well. The capability to
Drive() and the
Name property are inherited from Car.
At the first sight the code can look a bit complicated, especially if you're a C# veteran. The
Fly() functions aren't defined inside
SuperCar, as you'd do in a C# class. Instead, we stored these methods/functions in the global context, and referenced them in
SuperCar, to avoid the memory leaks that were discussed earlier in this chapter. You can, however, define
SuperCar, without losing any functionality.
If you comment the execution of
SuperCar, it won't inherit the capabilities of
Car any more. If you make this test in FireFox, you'll see the following eloquent error message in the Error Console window of Firefox:
Inheritance Using Prototyping
In closure-based inheritance, the derived class inherits the base class methods and properties by "loading" them into itself. Here's the code again for your reference:
This is so very complicated! In practice you'll find that the code doesn't look that scary, although the complete theory is a little more complex than this. A nice article describing a few additional theoretical aspects can be found at http://mckoss.com/jscript/object.htm.
The new implementation of
SuperCar, this time using prototypes, is the following, with the inheritance mechanism highlighted. The
Here, instead of creating a
Car instance in
SuperCar's constructor, we declare