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

235
Vistas
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 Respuestas
Responde la pregunta

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