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

130
Visualizações
Why can't I call a static method from the constructor?

I'm getting into ES6 and trying to turn a class that's over 2700 lines long into a collection of small, easy-to-read files.

I'd like to move some initialization code from the constructor into their own methods. But I'm a bit stuck. Consider this code:

export default class Thingy {
  non_static_prop;

  initNonStaticStuff() {
  }

  constructor(args) {
    this.non_static_prop = 'some non-static prop set by the constructor'; // ok
    console.log(this.non_static_prop); // works as expected
    // now can we get a method to do the same thing?
    initNonStaticStuff(); // fails:
      /**
       * `Uncaught ReferenceError: initNonStaticStuff is not defined`
       */
    // So I guess we'll have to initialize everything here.
    // But then how am I supposed to make my code smaller and more modular?
  }
}

I'm confused. What options do I have to run code from the constructor?

I could, of course, call a static method instead, but then this wouldn't let me access non-static properties.

Another option I see is to ask the page that creates the instance to then run initNonStaticStuff() (e.g. say by way of a start() method), but I'd rather skip such a step if possible.

What did I miss?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just call it with this.initNonStaticStuff();

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