I am a Javascript and React enthusiast, and I absolutely love writing technical blogs. There's just something about the process of breaking down complex concepts and sharing my knowledge with others that really excites me. In my free time, I enjoy exploring my other passions, such as painting, gardening, cooking, and managing my food blog.
3 minute read
Static class features
Static fields and methods are not used on instances of a class.
Instead, they are called on the class itself
and are declared using the static keyword.
Static methods are often utility functions, such as functions to create or clone objects,
whereas static properties are useful for caches, fixed-configuration, or any other data we don’t need to be replicated across instances.
In ES2015, static public methods have been introduced. ES2022 adds the remaining static fields and methods:
Static public fields
Static private fields
Static private methods
Let’s talk about them in brief.
Static public fields
Static public fields are added to the class constructor at the time of class evaluation
using Object.defineProperty().
The static fields and methods can be accessed from the class itself.
Instances cannot access static fields and methods.
Static fields can only be accessed by static methods.
Shape.getMessage() throws an error -
TypeError: Shape.getMessage is not a function
This is because getMessage is not a static function
so it cannot be accessed by class name Shape.
We can fix this issue by making the below modification:
Inheritance for static fields and methods
Static fields and methods are inherited from the parent class.
Like private instance fields and methods,
static private fields and methods
are also defined with a hash (#) prefix.
Inheritance for private static fields and methods
Private static fields have a restriction.
Only the class which defines the private static field can access the field.
This can lead to unexpected behavior when using this.
In the above example, this refers to the Rectangle class.
It does not have access to the private field #color.
When we try to call Rectangle.getMessage(),
it cannot read #color and throws TypeError.
We can fix the issue by modifying code as below -
Static field proposal is stable and with a variaty of implementations shipped.