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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With