Inheritance

The previous example showed a new class that was derived directly from Object. To define a class which inherits from something else, the base class is passed as additional parameter is passed to Core.extend(). The base class parameter is provided first, before the object definition parameter:

Multiplier = Core.extend(Counter, {

    defaultMultiplier: 2,

    multiply: function(amount) {
        if (amount) {
            this.count *= amount;
        } else {
            this.count *= this.defaultMultiplier;
        }
    }
});

In this example, we define a Multiplier class which extends Counter. A new method, multiply is added. In the above case, we're simply re-using the existing constructor provider by Counter.

If, hypothetically, we need to do additional work in the constructor of Multiplier as well, we can rewrite it as follows with its own constructor:

Multiplier = Core.extend(Counter, {

    $construct: function(defaultIncrement, defaultMultiplier) {
        // Invoke super-constructor.
        Counter.call(this, defaultIncrement);
        if (defaultMultiplier) {
            this.defaultMultiplier = defaultMultiplier;
        }
    },

    multiply: function(amount) {
        if (amount) {
            this.count *= amount;
        } else {
            this.count *= defaultMultiplier;
        }
    }
});

Calling the Base Class Constructor

The implementation of Multiplier above has overridden the constructor of its base class, Counter. But for the class to work properly, the base class constructor must be invoked when the derived class is instantiated. This can be accomplished using JavaScript's built in Function.call() method. Function.call() enables one to invoke a method with the this-pointer set to an arbitrary value. To call the base class constructor and have it operate on our new instance of Multiplier, we set the this-pointer to be our new class instance. The first parameter of Function.call() is the desired this-pointer value, and any additional methods are passed to the invoked function. In the above case we send defaultIncrement to be handled by Counter's constructor.