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:
- A JavaScript class cannot have a member property. You can only create it using a constructor
- 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,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo { | |
constructor(goal) { | |
this.goal = goal; | |
Foo.prototype.objectcount++; | |
} | |
} | |
Foo.prototype.objectcount = 0; |
Leave a Reply