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

136
Vistas
Workaround for ES6 class to have multiple constructors?

I'm trying to create an ES6 class with two constructors. The code looks something like this:

class MyClass {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }

  constructor(c) {
    this.a = c;
    this.b = c;
  }
}

But I'm getting the syntax error Uncaught SyntaxError: A class may only have one constructor. Is there any workaround that would let me have multiple constructors or am I just limited constructor in JS?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

JavaScript doesn't have built-in overloading. But you can do what you want using a default argument.

class myClass {
    constructor(a, b = a) {
        this.a = a;
        this.b = b;
    }
}

If it's not as simple as your example, you can give b some other default that's not a possible actual value. Then you can check if the value is the default and run different code.

class myClass {
    constructor(a, b = undefined) {
        if (b === undefined) {
            // do the 1-argument initialization
        } else {
            // do the 2-argument initialization
        }
    }
}
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