Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading