[英]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.
伪枚举的方式是通常的方式,即在对象上创建属性,但是,如果您尝试从不包含对象的对象中检索属性,则无法使JavaScript引擎抛出错误。存在。 Instead, the engine will return
undefined
. 相反,引擎将返回
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
. ...失败,出现
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 : 现在不推荐使用普通javascript对象中的自定义设置方法和获取方法,一种解决方案是为您的对象定义一个类和一个
set
函数:
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" .
这听起来像是“试图在javascript中强制Java功能” 。 You probably don't need this.
您可能不需要这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.