javascript权威指南-js的枚举

// 来自JavaScript权威指南219页

// 这个是一个工厂方法,每次调用都返回一个新的枚举类。

// 参数对象表示类的每个实例的名字和值

// 不能使用这个返回的枚举类创建新的实例。

// 枚举值继承自返回的这个枚举类

function enumeration (namesToValues) {

var enumeration = function () {

throw "Can`t Instantiate Enumerations"

}

var proto = enumeration.prototype = {

constructor: enumeration,

toString () {

return this.name

},

valueOf () {

return this.value

},

toJSON () {

return this.name

}

}

enumeration.values = []

for (name in namesToValues) {

var e = Object.create(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])

}

return enumeration

}

var Coin = enumeration({

Penny: 1,

Nickel: 5,

Dime: 10,

Quarter: 25

})

var c = Coin.Dime

// 每个值都是这个枚举类的实例

console.log(c instanceof Coin)

console.log(Coin.Dime == 10)

console.log(Number(Coin.Dime))

猜你喜欢

转载自blog.csdn.net/zsnpromsie/article/details/83376045