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 following diagram describes these two classes:
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
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: