Javascript ES6 - Enumerates inner classes used externally as a static enumeration

I would like to ask if it is possible to add an enumeration like this:

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

inside the class and be able to use it in some other file with something similar to: object.updateState(Class.STATES.HIDDEN)without the need to create a new object, such asboxObject.updateState(new Box().STATES.HIDDEN)

Thank.

+4
source share
2 answers

like this:

export class Foo{}
Foo.SomeStaticEnum={BAR:"bar"};

but const export looks more appropriate ...

export const FOO={BAR:"bar"};
+5
source

You can achieve static data properties in several ways:

Use destination :

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 :

Object.defineProperty,

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

getter:

ES6 . , .

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

, , n00dl3. ES6, :

export const BOX_STATES = {
  WIP: "Work in progress",
  ONLINE: "Online",
  ONLINE_MODIFIED: "Online, modified",
  HIDDEN: "Hidden"
};

export default class Box {};

, :

import { BOX_STATES } from './path-to-box';

console.log(BOX_STATES.WIP); // Work in progress is the output
+10

Source: https://habr.com/ru/post/1673119/


All Articles