Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda