Class details link
A static method
static classMethod() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
A.classMethod();
// hello
Copy the code
The static keyword precedes the classMethod method of class A, indicating that it is A static method that can be called directly on class A rather than on an instance
Calling a static method on instance A throws an error indicating that no change method exists.
If a static method contains the this keyword, this refers to the class, not the instance.
The static method classMethod calls this.baz, where this refers to class A, not an instance of A, the same as calling A.baz. Also, as you can see from this example, static methods can have the same name as non-static methods.
Static methods of a parent class that can be inherited by subclasses.
Static attributes
Static properties refer to properties of the Class itself, class.propName, not properties defined on the instance object (this).
This is done by adding the static keyword before the instance attribute.
class MyClass {
static myStaticProp = 42;
constructor() {
console.log(MyClass.myStaticProp); / / 42}}Copy the code