Javascript ES6 - Enums inside classes used outside like a static enum
You can achieve static data properties in multiple ways:
Use assignment:
const STATES = {
WIP: "Work in progress",
ONLINE: "Online",
ONLINE_MODIFIED: "Online, modified",
HIDDEN: "Hidden"
};
class Box {};
Box.STATES = STATES;
console.log(Box.STATES.WIP); // Work in progress is the output
Use Object.defineProperty:
When you use Object.defineProperty you could make it read-only
const STATES = {
WIP: "Work in progress",
ONLINE: "Online",
ONLINE_MODIFIED: "Online, modified",
HIDDEN: "Hidden"
};
class Box {};
Object.defineProperty(Box, 'STATES', {
value: STATES,
writable: false, // makes the property read-only
});
console.log(Box.STATES.WIP); // Work in progress is the output
Use static getter:
You can use ES6 static getter syntax to add the property in the class definition. You can make it read-only too defining just the getter.
const STATES = {
WIP: "Work in progress",
ONLINE: "Online",
ONLINE_MODIFIED: "Online, modified",
HIDDEN: "Hidden"
};
class Box {
static get STATES() {
return STATES;
}
}
console.log(Box.STATES.WIP); // Work in progress is the output
All that being said, I agree with n00dl3. If you are using ES6 modules, using a named export seems more appropiate:
export const BOX_STATES = {
WIP: "Work in progress",
ONLINE: "Online",
ONLINE_MODIFIED: "Online, modified",
HIDDEN: "Hidden"
};
export default class Box {};
So you can import it like this:
import { BOX_STATES } from './path-to-box';
console.log(BOX_STATES.WIP); // Work in progress is the output
If you don't need pure ES6 and can use Typescript, please prefer it. Typescript has a nice ENUM with export options
Example:
export enum STATES
{
WIP = "Work in progress",
ONLINE = "Online",
ONLINE_MODIFIED = "Online, modified",
HIDDEN = "Hidden"
}
export class SocialMedia
{
static state: STATES = STATES.HIDDEN;
}
console.log(SocialMedia.state);
SocialMedia.state = STATES.WIP;
console.log(SocialMedia.state);
Result:
Hidden
Work in progress
like this :
export class Foo{}
Foo.SomeStaticEnum={BAR:"bar"};
but exporting a const seems more appropriate...
export const FOO={BAR:"bar"};