javascriptecmascript-6javascript-objects

Is it possible to achieve multiple inheritance with ES6 classes?


I am trying to merge statics and prototypes of several classes in to 1 masterclass like in the example below.

Is that actually possible? My goal is that im able to merge the statics and prototypes to do things like:

Alltogether.dosomething() or Alltogether.o3.myoption1

// class1
class Option1 {
    constructor(properties) {
        this.o = {};
        this.o.myoption1 = properties.o.myoption1;
        this.o.myoption2 = properties.o.myoption2;
    }
    dosomething1() {
        return "o1";
    }
}

// class2
class Option2 {
    constructor(properties) {
        this.o2 = {};
        this.o2.myoption1 = properties.o2.myoption1;
        this.o2.myoption2 = properties.o2.myoption2;
    }
    dosomething2() {
        return "o2";
    }
}

// class3
class Option3 {
    constructor(properties) {
        this.o3 = {};
        this.o3.myoption1 = properties.o3.myoption1;
        this.o3.myoption2 = properties.o3.myoption2;
    }
    dosomething3() {
        return "o3";
    }
}

// now i want to create a super class with the 3 classes above
// however this doesnt work...
class Alltogether extends (Option1, Option2, Option3) {
    constructor(properties) {
        //........
    }
}

// My goal is that im able to merge the statics and prototypes to do things like
// Alltogether.dosomething()  // o2
// or Alltogether.o3.myoption1


Solution

  • Make it simple and use composition over inheritance:

    class Option {
        constructor(properties) {
            this.myoption1 = properties.myoption1;
            this.myoption2 = properties.myoption2;
        }
        dosomething() {
            return "o";
        }
    }
    
    class Alltogether {
        constructor(properties) {
            this.o = new Option(properties.o)
            this.o1 = new Option(properties.o1)
            this.o2 = new Option(properties.o2)
        }
    }
    

    If your dosomethings are actually that different, you can use multiple Option (sub)classes. If not, you should even consider using arrays instead of three numbered properties.