Categories
JavaScript Answers

How to make a “public static field” in a JavaScript class?

Spread the love

Sometimes, we want to make a "public static field" in a JavaScript class.

In this article, we’ll look at how to make a "public static field" in a JavaScript class.

How to make a "public static field" in a JavaScript class?

To make a "public static field" in a JavaScript class, we can create a static getter.

For instance, we write

class Agent {
  static get CIRCLE() {
    return 1;
  }
  static get SQUARE() {
    return 2;
  }
}

console.log(Agent.CIRCLE);

to define the CIRCLE and SQUARE getters in the Agent class.

Then we access them like Agent.CIRCLE.

Conclusion

To make a "public static field" in a JavaScript class, we can create a static getter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *