Home > Back-end >  how can I call a method only one time in a class? (first time when add "new")
how can I call a method only one time in a class? (first time when add "new")

Time:08-19

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

CodePudding user response:

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();

  • Related