Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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!');
        }
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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()

about 4 years ago · Juan Pablo Isaza Denunciar

0

It feels a bit weird, but a solution to this was to split it up into multiple steps. If the super class is declared, it can be referred to in a second step, obviously.

MDN: Class expressions must be declared before they can be used

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

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

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

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

If there is a way to do it in one step, I'd still like to know.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda