1

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

2

2 Answers 2

1

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.)

    0

    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.

    2
    • Why setter, why not getter?
      – VisioN
      CommentedFeb 19, 2013 at 10:41
    • I mean the OP wants to throw exception if he gets the invalid property.
      – VisioN
      CommentedFeb 19, 2013 at 10:47

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.