Mediator
Mediator

Reputation: 15378

How create enum in javascript

I need create named constant.

for example:

NAME_FIELD: {
            CAR : "car", 
            COLOR: "color"}

using:

var temp = NAME_FIELD.CAR // valid
var temp2 = NAME_FIELD.CAR2 // throw exception

most of all I need to make this enum caused error if the key is not valid

Upvotes: 1

Views: 1070

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074485

most of all I need to make this enum caused error if the key is not valid

Unfortunately, you can't. The way you're doing pseudo-enums is the usual way, which is to create properties on an object, but you can't get the JavaScript engine to throw an error if you try to retrieve a property from the object that doesn't exist. Instead, the engine will return undefined.

You could do this by using a function, which obviously has utility issues.

Alternately (and I really don't like this idea), you could do something like this:

var NAME_FIELD$CAR = "car";
var NAME_FIELD$COLOR = "color";

Since you would access those as free identifiers, trying to read a value that didn't exist:

var temp2 = NAME_FIELD$CAR2;

...fails with a ReferenceError. (This is true even in non-strict mode code; the Horror of Implicit Globals only applies to writing to a free identifier, not reading from one.)

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382160

Now that custom setters and getters in plain javascript objects are deprecated, a solution could be to define a class for your object and a set function :

NAME_FIELD= {
     CAR : "CAR", 
     COLOR: "COLOR"
};

function MyClass(){
}
MyClass.prototype.setProp = function (val) {
  if (!(val in NAME_FIELD)) throw {noGood:val};
  this.prop = val;
}
var obj = new MyClass();

obj.setProp(NAME_FIELD.CAR); // no exception
obj.setProp('bip'); // throws an exception

But as enums aren't a native construct, I'm not sure I would use such a thing. This smells too much as "trying to force a java feature in javascript". You probably don't need this.

Upvotes: 0

Related Questions