如下,我们来定义Week的枚举:
var WeekDay = {};
WeekDay.Sunday = 0;
WeekDay.Monday = 1;
WeekDay.Tuesday = 2;
WeekDay.Wedesay = 3;
WeekDay.Thursday = 4;
WeekDay.Friday = 5;
WeekDay.Saturday = 6;
}
当然,我们有更为直观的方式。以定义DOM文档节点类型为例,定义方式如下:
var Node = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGEMENT_NODE: 11,
NOTATION_NODE: 12
}
}
与类C语言类似,以上2个例子的枚举对应属性值均为整形。你可能想到,难道还能定义成别的类型?要回答这个问题,得先知道咱们这个枚举实现的原理。前面说到,这里是用JSON来实现的,而JSON可以使用任何类型的值!所以,Js中的枚举可以是任何类型的值。以下以String类型为例:
var Color = {
Color1: 'red',
Color2: 'green',
Color3: 'white',
Color4: 'black'
}
}
以更为复杂的类型来定义一个PersonList枚举如下:
var PersonList = {
ZhangSan: {
Id: 1,
Name: 'ZhangSan',
Gender: 'man'
},
LiSi: {
Id: 2,
Name: 'LiSi',
Gender: 'woman'
},
ZhaoWu: {
Id: 3,
Name: 'ZhaoWu',
Gender: 'man'
}
}
}