Metodi statici JavaScript
I metodi di classe statici sono definiti sulla classe stessa.
Non puoi chiamare un static
metodo su un oggetto, solo su una classe di oggetti.
Esempio
class Car {
constructor(name) {
this.name =
name;
}
static hello() {
return "Hello!!";
}
}
let myCar = new Car("Ford");
// You can call 'hello()' on
the Car Class:
document.getElementById("demo").innerHTML
= Car.hello();
// But NOT on a Car Object:
// document.getElementById("demo").innerHTML
= myCar.hello();
// this will raise an error.
Se vuoi utilizzare l'oggetto myCar all'interno del static
metodo, puoi inviarlo come parametro:
Esempio
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);