Metody statyczne w JavaScript

Statyczne metody klasy są zdefiniowane w klasie samej.

Nie można wywołać na obiekcie static Metoda można wywołać tylko na klasie obiektowej.

Instancja

class Car {
  constructor(name) {
    this.name = name;
  }
  static hello() {
    return "Hello!!";
  }
}
let myCar = new Car("Ford");
// Możesz wywołać 'hello()' na klasie Car:
document.getElementById("demo").innerHTML = Car.hello();
// Ale nie możesz wywołać go na obiekcie Car:
// document.getElementById("demo").innerHTML = myCar.hello();
// To spowoduje błąd.

Spróbuj sam

Jeśli chcesz użyć static Możesz użyć obiektu myCar w metodzie, aby wysłać go jako parametr:

Instancja

class Car {
  constructor(name) {
    this.name = name;
  }
  static hello(x) {
    return "Hello " + x.name;
  }
}
let myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);

Spróbuj sam