javascriptは後端と同じエニュメレーションEumオブジェクトを実現します.
8123 ワード
1 ;
2 (function (global, undefined) {
3
4 global.Enum = function (namesToValues) {
5 var enumeration = function () {
6 throw "can't Instantiate Enumerations";
7 };
8 enumeration.setValue = function (x) {
9 var val = null;
10 enumeration.foreach(function (i) {
11 if (i.value == x) {
12 val = enumeration[i.name];
13 }
14 }, null);
15 return val;
16 };
17
18 function inherit(superCtor) {
19 var f = function () {
20 };
21 f.prototype = superCtor;
22 var ctor = function () {
23 };
24 ctor.prototype = new f();
25 ctor.prototype.constructor = superCtor.constructor;
26 return new ctor;
27 }
28
29 var proto = enumeration.prototype = {
30 constructor: enumeration,
31 toString: function () {
32 return this.name;
33 },
34 valueOf: function () {
35 return this.value;
36 },
37 toJSON: function () {
38 return this.name;
39 }
40 };
41
42 enumeration.values = [];
43
44 for (name in namesToValues) {
45 var e = inherit(proto);
46 e.name = name;
47 e.value = namesToValues[name];
48 enumeration[name] = e;
49 enumeration.values.push(e);
50
51 }
52
53 enumeration.foreach = function (f, c) {
54 for (var i = 0; i < this.values.length; i++) {
55 f.call(c, this.values[i]);
56 }
57 };
58
59 return enumeration;
60
61 };
62 })(window);
var Qos = window.Enum({
AT_MOST_ONCE: 0,
AT_LEAST_ONCE: 1,
EXACTLY_ONCE: 2,
DEFAULT: 3
});
今はQos.ATを印刷します.MOST_ONCEは現実の対象になりますが、私達が進行する時には Q os.AT_MOST_OCE==1比較時はtrueです.しかもQos.setValue(1)と Q os.AT_MOST_OCE同じQ os.AT_MOST_Onese.toString()->'AT_MOST_OCE; Q os.AT_MOST_ONSCE.valueOf()->1;Q os.AT_MOST_Onese.name->'AT_MOST_OCE;Q os.AT_MOST_OCE .value->>1
はい、バックエンドの言語特性と同じEumオブジェクトが登場しました!!
転載先:https://www.cnblogs.com/doublenet/p/4390817.html