JavaScript statiese metodes
Statiese klasmetodes word op die klas self gedefinieer.
Jy kan nie 'n static
metode op 'n objek noem nie, slegs op 'n objekklas.
Voorbeeld
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.
As jy die myCar-voorwerp binne die static
metode wil gebruik, kan jy dit as 'n parameter stuur:
Voorbeeld
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);