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

223
Visualizações
how can I call a method only one time in a class? (first time when add "new")

I have a long code with a lot method, but since I am on stackoverflow I will add to you a simple minimal example here (is not the final, but I hope show you the bug):

I have a code like this:

class MyClass {
  constructor() {
    this.myMethod();
  }

  myMethod() {
    console.log("hello world!")
  }
}

new MyClass();

and this code is ok.

the method runs once.

but if I call it more than 2+ times it will run the method another time.

/* other code  */
new MyClass();
new MyClass();
new MyClass();
new MyClass();
new MyClass();

// wrong output:
hello world
hello world 
hello world
...

// desired output (only one time)
hello world

if you are interested in why run one time. this is because I want that the class created some Ui elements at the first but then get the generated ui and change the things with the given parameters in constructor

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

check this documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

there is a keyword for classes that do this thing called static

class MyClass {
  // no () just static and { your code }
  static {
    console.log("called once");
  }

  myOtherMethod() {
    console.log("run when I want or every time")
  }
}

/* other code  */
new MyClass();
new MyClass();
new MyClass();
new MyClass();
new MyClass();

about 4 years ago · Santiago Trujillo 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