javascript實現與後端相同的枚舉Enum對象

來源:互聯網
上載者:User

標籤:

 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實現與後端相同的枚舉Enum對象

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.