Javascript constructor with enumeration value as argument

827 views Asked by At

I would like to create an object that can take one of a fixed set of input strings as an argument in the constructor. In order to constrain the possible strings, I would like to use an enumeration-type construction.

What I have so far is a solution that relies on two separate functions: one uses the Revealing Module pattern (I think) to expose the fixed set of strings, like this:

var MyEnum = (function() {
    var stringA = "string A";
    var stringB = "string B";
    var stringC = "string C";

    return {
        stringA: stringA,
        stringB: stringB,
        stringC: stringC
    };
})();

The second function takes as input one of the string values (along with other values) as arguments for construction. For instance, given a function called MyObject, this is how I call it:

var myInstance = new MyObject(MyEnum.stringB, 42, "blue");

What I want to know is this: Is there an alternate architecture that combines MyEnum and MyObject into a single entity? MyEnum is not used by anything else, but it was the only way I could find to have the instances of the strings available to the MyObject constructor.

I tried somehow making the enumeration values available through a prototype method on MyObject, but the problem is that the method doesn't "exist" until the object is instantiated.

For background, I'm coming from the land of C#, so I know my thinking is biased in that direction, and maybe the solution is more psychological than technical.

Any help is appreciated.

EDIT: It's been pointed out the revealing module pattern is unnecessary here, which I understand and agree with. That was a vestigial structure from an earlier attempt to solve this problem. At this point, I don't know if it's preferable to edit the RM pattern out (since it's irrelevant to the question) or if this edit is sufficient. I'd prefer to hide my shame, but I can also own a mistake...

2

There are 2 answers

3
levi On BEST ANSWER

You can attach static properties to the function object:

function Painter(color) {

}

Painter.Color = {
    RED: "color_red",
    BLUE: "color_blue"
};

var painter = new Painter(Painter.Color.BLUE);

There no need for the revealing pattern when defining the enum, since you are exposing everything anyways.

0
jherax On

If you want all this things encapsulated in the same object you can follow the approach Everything is an object

//constructor definition
function Contructor(arg1, arg2) {
  //use Contructor.values
  //implementation
}

//defines the set of values as a property of the constructor
Contructor.values = {
  stringA: "string A",
  stringB: "string B",
  stringC: "string C"
};

Or if you want pass it as an argument:

//constructor definition
function Contructor(value, arg1, arg2) {
  //implementation
}

var obj = new Contructor(Contructor.values.stringA, 42, "blue");