I used to create classes with type property in usual OOP languages like swift, or java:
struct ClassA { enum Type { case b, c, d } var type: Type }
and then use it like
let a = ClassA(type: .b)
In es6 similar construction will be:
const Type = { a: 0, b: 1, c: 2, } class ClassA { constructor(type) { this.type = type } }
Issues with this from my perspective are next:
- To build a ClassA object user has to import Type as well
- Type doesn't seem like a part of ClassA
Is my code is okay for Javascript? Described problems are okay in Javascript? Is there any better approach for this?
Current problem I'm trying to solve is next
I have several types of user activities represented as objects. They share lots of similarities like name, date, duration etc., but have to be displayed depending on their types.
My solution was to give all objects essential fields with their types.
Type
a property ofClassA
, but that’s not really any better.class
syntax fool you. This is syntax sugar. There are no classes in Javascript. Never have been, never will be.