0

I have a class that only holds a static method, and there is no need to ever instantiate it. I want this class to wrap an "enum" with static values, to be used by the static method under this class. Here is a simplified example of this use case as i "wanted" it too look like:

class UserActionsService {

    static actionTypes = {
        foo: 1,
        bar: 2,
        buzz: 3
    };

    static doSomethingWith(actionType) {
        console.log(actoinType);
    }
}

and the usage should have look like:

UserActionsService.doSomethingWith(UserActionsService.actionTypes.buzz);

But, since i couldn't make the static actionTypes member work, i wrapped it with a static function like so:

class UserActionsService {

    static actionTypes() {
        return {
            foo: 1,
            bar: 2,
            buzz: 3
        };
    }

    static doSomethingWith(actionType) {
        console.log(actoinType);
    }
}

And use it like this:

UserActionsService.doSomethingWith(UserActionsService.actionTypes().buzz);
///////////////////////////////////////////////// Ugly part here ^^ 

It works, but ugly. Am i missing something? Is there a specific reason that makes only static methods available, and not static members?

Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25

2 Answers2

2

You can use a getter to get around the "ugly" syntax

class UserActionsService {

    static get actionTypes() {
      return {
        foo: 1,
        bar: 2,
        buzz: 3
       };
    }

    static doSomethingWith(actionType) {
        console.log(actionType);
    }
}

UserActionsService.doSomethingWith(UserActionsService.actionTypes.buzz);
Gorka Hernandez
  • 3,890
  • 23
  • 29
  • "*Your code should work as is*" Of course it's not. It's syntaticaly invalid, as properties are not supported. – dfsq Feb 22 '18 at 12:33
  • You are correct, I incorrectly assumed he was using a transpiler such as Babel, which would let you do that. Edited the answer, thanks for the input. – Gorka Hernandez Feb 22 '18 at 12:36
1

If you're using modules, you can just make your 'enum' a plain object, on the same level as your static function, and export both as properties of a module:

UserActionsService.js

const actionTypes = {
  foo: 1,
  bar: 2,
  buzz: 3
}

function doSomethingWith(actionType){
   do the thing...
}

module.exports = {actionTypes, doSomethingWith};

Consuming module

const UserActionsService = require('./UserActionsService');
UserActionsService.doSomethingWith(UserActionsService.actionTypes.buzz);

The ES6 'class' is really syntactic sugar in this context, and doesn't provide anything that this simple structure doesn't give you.

As far as why you can't do what you originally tried to do, it isn't (as commented by dsfq) supported syntax.

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30