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


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


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.

链接地址: http://www.djcxy.com/p/91778.html

上一篇: 如何在Enumeration中获取int枚举值

下一篇: 如何在JavaScript中创建枚举