Search code examples
javascriptinheritanceconstructorprototypechaining

Inheritance: Constructor doesn't run "super"?


I've run into this behavior after using JS for a few months. I'm very puzzled because of my Java background: I create a class and make subclasses. Call a subclass' constructor won't call the parent constructor. Ok, I read about this behavior, it seems normal, right?

See this jsfiddle example to help me clarify.

So to have my subclass constructor run each of its parent constructor, I'm adding the following (see jsfiddle example

Ok, seems to work better this way. Now, I'm wondering about the following; Is there a way to specify wich is the superclass without trigger its constructor? Like for instance the following runs the Node() method:

GameObject.prototype = new Node();
GameObject.prototype.constructor=GameObject;

(see updated jsfiddle example)

I can't help but feel I'm not doing it right. As my real model is layered across 7 subclasses, there's a total of 21 calls to my constructors (6 + 5 + 4 + 3 + 2 + 1 = 21).

Am I doing something wrong? Thanks for your time!


Solution

  • Generally, you're doing it right. But your constructor function creates properties on its instances and those properties get assigned to the inheriting constructor's prototype.

    Subclass.prototype.animations, for example are on the prototype, shared by all further instances of Subclass. From your code it seems like you intended these animations to be created anew for each instance.

    How to resolve this problem? Don't use constructor functions at all. Use object literals and Object.create.

    var Node = {
        init: function () { this.animations = []; },
        doSomething: function () { console.log(this.animations); }
    };
    
    var GameObject = Object.create(Node);
    GameObject.doSomethingElse = function () { this.init(); this.doSomething(); }
    

    Instantiate the same way you inherit:

    var gameObj = Object.create(GameObject);
    gameObj.doSomethingElse();
    

    It shouldn't be more difficult than that.

    See Combining inheritance with the module pattern.