javascript实现与后端相同的枚举Enum对象

 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会现实一个对象,但是当我们进行 Qos.AT_MOST_ONCE==1 比较时为true;而且Qos.setValue(1) 与 Qos.AT_MOST_ONCE相同

Qos.AT_MOST_ONCE.toString() -> 'AT_MOST_ONCE' ; Qos.AT_MOST_ONCE.valueOf() -> 1 ; Qos.AT_MOST_ONCE.name -> 'AT_MOST_ONCE' ; Qos.AT_MOST_ONCE .value -> 1;

好,现在一个特点与后端语言特性相同的Enum对象就此出现了!!!

你可能感兴趣的:(JavaScript)