标签:javascript
function enumeration(namesToValues) { var enumeration = function() { throw "Can't Instantiate Enumeration"} var proto = enumeration.prototype = { constructor: enumeration, toString: function() { return this.name; }, valueOf: function() { return this.value; }, toJSON: function() { return this.name; } }; enumeration.values = []; for(name in namesToValues) { var e = inherit(proto); e.name = name; e.value = namesToValues[name]; enumeration[name] = e; enumeration.values.push(e); } enumeration.foreach = function(f, c) { for (var i = 0; i < this.values.length; i++) { f.call(c, this.values[i]); }; }; Object.freeze(enumeration.values); Object.freeze(enumeration); return enumeration; } function inherit(p) { if (p == null) throw TypeError(); if (Object.create) return Object.create(p); var t = typeof p; if (t !== "object" && t !== "function") throw TypeError(); function f() {}; f.prototype = p; return new f(); } var Coin = enumeration({Penny: 1, Nickel:5, Dime:10, Quarter:25}); var c = Coin.Dime; c instanceof Coin; c.constructor == Coin;
JavaScript 实现枚举类型,布布扣,bubuko.com
标签:javascript
原文地址:http://blog.csdn.net/bzq9012/article/details/38729987