How to Use Static Properties in a JavaScript Class?

Estimated read time 1 min read

Static properties in a JavaScript class are properties that are shared among all instances of a class, rather than being unique to each instance. You can use static properties to store data that is associated with the class as a whole, rather than with individual instances.

Here’s an example of how to use static properties in a JavaScript class:

class Circle {
  static pi = 3.14;

  constructor(radius) {
    this.radius = radius;
  }

  static circumference(radius) {
    return 2 * Circle.pi * radius;
  }
}

const circle = new Circle(10);
console.log(Circle.circumference(circle.radius)); // 62.8

In this example, the Circle class has a static property pi and a static method circumference. The static property pi is a constant value that is shared by all instances of the class, and the static method circumference calculates the circumference of a circle given its radius.

To access a static property or method, you use the name of the class followed by the dot operator (.) and the property or method name, like this: ClassName.propertyName or ClassName.methodName().

Static properties and methods are useful when you want to maintain state or behavior that is shared across all instances of a class, rather than being unique to each instance.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply