Search code examples
javascriptinheritancemultiple-inheritanceeaseljscreatejs

Inherit two classes - Javascript


I'm creating a new class definition Button that extends an existing Container class in EaselJS. There are no problems with that. However, I'd also like Button to inherit from a super class All, so that Button also has access to its .banana and .eatBanana. How do I go about this?

(function() {

    function All() {
        this.banana = 0;
    }
    var p = All.prototype;

    p.eatBanana = function() {
        alert(this.banana);
    }

    window.All = All;
}());

(function() {

    function Button(apple) {
        this.apple = apple || 0;
        this.Container_constructor();
    }
    var p = createjs.extend(Button, createjs.Container);

    p.sayHi = function() {
       alert(this.apple + this.banana);
    }

    window.Button = createjs.promote(Button, 'Container');
}());

Solution

  • Javascript, and by extension CreateJS, does not support multiple inheritance. You could:

    1. rethink your inheritance structure (ex. have Button extend All which extends Container)
    2. mix-in members from All into your Button class or instances: Button.prototype.doSomething = All.prototype.doSomething or myButton.doSomething = All.prototype.doSomething.
    3. inject members into a super class such as DisplayObject that is extended by all of the classes you want the members on: DisplayObject.prototype.doSomething = All.prototype.doSomething.