Declaring static constants in ES6 classes?
Achieve static constants in an ES6 class employing static getters. This technique enables property access on the class rather than an instance:
This paradigm ensures immutability and ties the value tightly to the class.
Stone-cold immutability with Object.freeze()
Enhance the immutability level of your constants to "Sub-Zero" by using Object.freeze()
on them. It guarantees read-only properties:
Using Object.freeze()
makes the constant’s properties unchangeable, maintaining stability and integrity.
The ES7 crystal ball
Future-proof your work using the ES7 proposal for class properties. With the magic wand known as @babel/plugin-proposal-class-properties, your code ascends to a higher plane:
Remember, using this incantation requires a build step with Babel and might trigger "Witch!" cries in less modern environments.
Constants: the community way
Export your constants from the module containing the class. It brings organization and peace to the land:
The modularity of this approach aids in maintainability leading to a happy kingdom of code.
Constants without static getters
A fallback approach for defining constants is employing Object.defineProperty()
. This method sets non-writable properties:
This strategy creates a property that stands strong against re-assignments or overwrites.
Alert: Stay away from prototype manipulation
Avoid direct handling of the prototype
to declare constants. Unanticipated side effects may occur:
This adds the constant on every instance rather than the class, spiraling away from a true static constant.
Was this article helpful?