How to add a static member property in a JavaScript class?

Recently while solving a problem, I came across a requirement to create a property in a JavaScript class, which needs to be shared by all the object instances. In the programming world, these types of properties are called Static Properties.

There are various scenarios when you need a static member property:

  • When counting number of object instances created from a particular class
  • When logging some information at the class level instead of object instance level, etc.

To create a static property, you should know two important things:

  1. A JavaScript class cannot have a member property. You can only create it using a constructor
  2. Like the function constructor, a JavaScript class also has a prototype

Well, if you are a champion of prototypes, you must have guessed the answer in your mind by this time.  Any way, let us move forward to see the implementation,


class Foo {
constructor(goal) {
this.goal = goal;
Foo.prototype.objectcount++;
}
}
Foo.prototype.objectcount = 0;

Read full article on the Infragistics blog

One response to “How to add a static member property in a JavaScript class?”

  1. Thank you DJ Sirji!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com