码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 实现枚举类型

时间:2014-08-21 15:01:14      阅读:226      评论:0      收藏:0      [点我收藏+]

标签: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;

权威指南上的。enumeration函数里定义的enumeration变量和函数名的enumeration有关系吗?把这个变量换成whatever这个名字好像也没什么影响。

JavaScript 实现枚举类型,布布扣,bubuko.com

JavaScript 实现枚举类型

标签:javascript

原文地址:http://blog.csdn.net/bzq9012/article/details/38729987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!