Object of class and subclass expressions in Javascript

Is there a way in Javascript to make an Object containing expressions of both classes and subclasses of it? I tried this way, but I guess I can’t refer to the superclass this way.

const myClasses = {
    'animal': class {
        a;
        b;

        constructor(x, y) {
            this.a = x;
            this.a = y;
        }
    },
    'dog': class extends animal {
        constructor(d, e) {
            super(d, e);
        }

        bark () {
            console.log('woof!');
        }
    }
}

>Solution :

It looks like the OP is aiming for an index of classes that can be instantiated based on a key. How about, define the classes as you normally would, then refer to them in the index…

class animal {
  a;
  b;

  constructor(x, y) {
    this.a = x;
    this.a = y;
  }
}

class dog extends animal {
  constructor(d, e) {
    super(d, e);
  }

  bark() {
    console.log('woof!');
  }
}

const myClasses = { animal, dog };

const myAnimalName = 'dog';
const klass = myClasses[myAnimalName];

const myAnimal = new klass()
myAnimal.bark()

Leave a Reply