class Thing {
static type = 'thing';
static myType() {
return `This class has a type of ${this.type}`;
}
}
console.log(Thing.type);
//=> 'thing'
console.log(Thing.myType());
//=> 'This class has a type of thing'
// Instances do not inherit static fields and methods
const t = new Thing();
console.log(t.type);
//=> undefined
console.log(t.myType())
//=> Uncaught TypeError: t.myType is not a function
class ClassWithStaticMethod {
static staticProperty = 'someValue';
static staticMethod() {
return 'static method has been called.';
}
static {
console.log('Class static initialization block called');
}
}
console.log(ClassWithStaticMethod.staticProperty);
// output: "someValue"
console.log(ClassWithStaticMethod.staticMethod());
// output: "static method has been called."
//------------------syntex-------------------------
static methodName() { /* ... */ }
static propertyName [= value];
// Class static initialization block
static {
}
// static in class javascript
// Static class methods are defined on the class itself.
// You cannot call a static method on an object, only on an object class.
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.