Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!