JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

9.6.2 Example: Enumerated Types

9.6.2 Example: Enumerated Types


An enumerated type is a type with a finite set of values that are listed (or “enumerated”) when the type is defined. In C and languages derived from it, enumerated types are declared with the enum keyword. enum is a reserved (but unused) word in ECMAScript 5 which leaves open the possibility that JavaScript may someday have native enumerated types. Until then, Example 9-7 shows how you can define your own enumerated types in JavaScript. Note that it uses the inherit() function from Example 6-1 .

Example 9-7 consists of a single function enumeration(). This is not a constructor function, however: it does not define a class named “enumeration”. Instead, this is a factory function: each invocation creates and returns a new class. Use it like this:

// Create a new Coin class with four values: Coin.Penny, Coin.Nickel, etc. var Coin = enumeration({Penny: 1, Nickel:5, Dime:10, Quarter:25}); var c = Coin.Dime; // This is an instance of the new class c instanceof Coin // => true: instanceof works c.constructor == Coin // => true: constructor property works Coin.Quarter + 3*Coin.Nickel // => 40: values convert to numbers Coin.Dime == 10 // => true: more conversion to numbers Coin.Dime > Coin.Nickel // => true: relational operators work String(Coin.Dime) + ":" + Coin.Dime // => "Dime:10": coerce to string

The point of this example is to demonstrate that JavaScript classes are much more flexible and dynamic than the static classes of languages like C++ and Java.

Example 9-7. Enumerated types in JavaScript

// This function creates a new enumerated type. The argument object specifies // the names and values of each instance of the class. The return value // is a constructor function that identifies the new class. Note, however // that the constructor throws an exception: you can't use it to create new // instances of the type. The returned constructor has properties that // map the name of a value to the value itself, and also a values array, // a foreach() iterator function function enumeration(namesToValues) {

// This is the dummy constructor function that will be the return value. var enumeration = function() { throw "Can't Instantiate Enumerations"; };

// Enumerated values inherit from this object.

var proto = enumeration.prototype = { constructor: enumeration, // Identify type toString: function() { return this.name; }, // Return name valueOf: function() { return this.value; }, // Return value

9.6 Object-Oriented Techniques in JavaScript | 217

toJSON: function() { return this.name; } // For serialization };

enumeration.values = []; // An array of the enumerated value objects

// Now create the instances of this new type.

for(name in namesToValues) { // For each value var e = inherit(proto); // Create an object to represent it e.name = name; // Give it a name e.value = namesToValues[name]; // And a value enumeration[name] = e; // Make it a property of constructor enumeration.values.push(e); // And store in the values array

} // A class method for iterating the instances of the class enumeration.foreach = function(f,c) {

for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]); };

// Return the constructor that identifies the new type return enumeration; }

The “hello world” of enumerated types is to use an enumerated type to represent the suits in a deck of cards. Example 9-8 uses the enumeration() function in this way and also defines classes to represents cards and decks of cards.1

Example 9-8. Representing cards with enumerated types

// Define a class to represent a playing card

function Card(suit, rank) { this.suit = suit; // Each card has a suit this.rank = rank; // and a rank

}

// These enumerated types define the suit and rank values Card.Suit = enumeration({Clubs: 1, Diamonds: 2, Hearts:3, Spades:4}); Card.Rank = enumeration({Two: 2, Three: 3, Four: 4, Five: 5, Six: 6,

Seven: 7, Eight: 8, Nine: 9, Ten: 10, Jack: 11, Queen: 12, King: 13, Ace: 14});

// Define a textual representation for a card Card.prototype.toString = function() {

return this.rank.toString() + " of " + this.suit.toString(); }; // Compare the value of two cards as you would in poker Card.prototype.compareTo = function(that) {

if (this.rank < that.rank) return -1; if (this.rank > that.rank) return 1; return 0;

};

// A function for ordering cards as you would in poker

1. This example is based on a Java example by Joshua Bloch, available at http://jcp.org/aboutJava/ communityprocess/jsr/tiger/enum.html .

Card.orderByRank = function(a,b) { return a.compareTo(b); };

// A function for ordering cards as you would in bridge

Card.orderBySuit = function(a,b) { if (a.suit < b.suit) return -1; if (a.suit > b.suit) return 1; if (a.rank < b.rank) return -1; if (a.rank > b.rank) return 1; return 0;

};

// Define a class to represent a standard deck of cards

function Deck() { var cards = this.cards = []; // A deck is just an array of cards Card.Suit.foreach(function(s) { // Initialize the array

Card.Rank.foreach(function(r) { cards.push(new Card(s,r)); }); }); }

// Shuffle method: shuffles cards in place and returns the deck

Deck.prototype.shuffle = function() { // For each element in the array, swap with a randomly chosen lower element var deck = this.cards, len = deck.length; for(var i = len-1; i > 0; i--) {

var r = Math.floor(Math.random()*(i+1)), temp; // Random number

temp = deck[i], deck[i] = deck[r], deck[r] = temp; // Swap } return this;

};

// Deal method: returns an array of cards

Deck.prototype.deal = function(n) { if (this.cards.length < n) throw "Out of cards"; return this.cards.splice(this.cards.length-n, n);

};

// Create a new deck of cards, shuffle it, and deal a bridge hand var deck = (new Deck()).shuffle(); var hand = deck.deal(13).sort(Card.orderBySuit);

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31381.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1