Javascript ES6 - Enums inside classes used outside like a static enum

Maxime M. picture Maxime M. · Mar 24, 2017 · Viewed 27.6k times · Source

I'd like to ask if it's possible to add an enum similar to:

STATES = {
    WIP: "Work in progress",
    ONLINE: "Online",
    ONLINE_MODIFIED: "Online, modified",
    HIDDEN: "Hidden"
}

inside a Class, and be able to use it in some other file with something similar to: object.updateState(Class.STATES.HIDDEN) without having to construct a new object like boxObject.updateState(new Box().STATES.HIDDEN)

Thank you.

Answer

pablogq picture pablogq · Mar 24, 2017

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