Search code examples
javascriptprototypeprototypejs

Is it okay to declare a new subclass as a prototype method in JavaScript?


I have a class that has a few nested subclasses, but I'm not sure what the correct syntax should be. This is what I was thinking of doing. It works out well, but maybe it's not the best coding practice.

function AClass() {
    this.myB = new BClass();
}

AClass.prototype.BClass() {
    this.myC = new CClass();
}

AClass.prototype.BClass.prototype.CClass() {
    // C constructor
}

Solution

  • If your nested classes are meant to only be used together with the main class, you could define them as (static) properties of the main class. There is no reason to have them available on every instance.

    function MainClass() {
        this.myB = new MainClass.SubClassB();
    }
    
    MainClass.SubClassB = function() {
        this.myC = new MainClass.SubClassC();
    }
    
    MainClass.SubClassC = function() {
        // C constructor
    }
    
    MainClass.SubClassC.prototype.sayHi = function(){ 
        console.log('Hi from C');
    }
    
    
    var myInstance = new MainClass();
    myInstance.myB.myC.sayHi();
    

    *) Note that the nested classes have no inheritance relationship with your main class. As @squint mentioned in the comment, the pattern you seem to want is composition, not inheritance.