Problem
You want to define a static property inside a “class”.
Ingredients
- 1 “class”
- 1 property
Directions
-
Create a “class”.
class SomeClass { constructor(property) { this.property = property; } }
-
Add the property that should be static directly to the “class”.
class SomeClass { constructor(property) { this.property = property; } } SomeClass.STATIC_PROPERTY = 'This is a static property.';
-
Voilá, there you got your static property.
console.log(SomeClass.STATIC_PROPERTY); // "This is a static property."
Notes
-
Static properties cannot be accessed via an instance:
let instance = new SomeClass(); // console.log(instance.STATIC_PROPERTY); // won't work
-
To access a static property based on an instance you need to access it via the
constructor
property:let instance = new SomeClass(); console.log(instance.constructor.STATIC_PROPERTY);