2015年2月14日 星期六

javascript-enum

http://stackoverflow.com/questions/287903/enums-in-javascript





var Colors = function(){
return {
    'WHITE':0,
    'BLACK':1,
    'RED':2,
    'GREEN':3
    }
}();

console.log(Colors.WHITE)  //this prints out "0"
if(currentColor == my.namespace.ColorEnum.RED) {
   // alert name of currentColor (RED: 0)
   var col = my.namespace.ColorEnum;
   for (var name in col) {
     if (col[name] == col.RED)
       alert(name);
   } 

}
Alternatively, you could make the values objects, so you can have the cake and eat it to:
var SIZE = {
  SMALL : {value: 0, name: "Small", code: "S"}, 
  MEDIUM: {value: 1, name: "Medium", code: "M"}, 
  LARGE : {value: 2, name: "Large", code: "L"}
};

var currentSize = SIZE.MEDIUM;
if (currentSize == SIZE.MEDIUM) {
  // this alerts: "1: Medium"
  alert(currentSize.value + ": " + currentSize.name);
}
In Javascript, as it is a dynamic language, it is even possible to add enum values to the set later:
// Add EXTRALARGE size
SIZE.EXTRALARGE = {value: 3, name: "Extra Large", code: "XL"};
Remember, the fields of the enum (value, name and code in this example) are not needed for the identity check and are only there for convenience. Also the name of the size property itself does not need to be hardcoded, but can also be set dynamically. So supposing you only know the name for your new enum value, you can still add it without problems:
// Add 'Extra Large' size, only knowing it's name
var name = "Extra Large";
SIZE[name] = {value: -1, name: name, code: "?"};
Ofcourse this means that some assumptions can no longer be made (that value represents the correct order for the size for example).
Remember, in Javascript an object is just like a map or hashtable. A set of name-value pairs. You can loop through them or otherwise manipulate them without knowing much about them in advance.
E.G:
for (var sz in SIZE) {
  // sz will be the names of the objects in SIZE, so
  // 'SMALL', 'MEDIUM', 'LARGE', 'EXTRALARGE'
  var size = SIZE[sz]; // Get the object mapped to the name in sz
  for (var prop in size) {
    // Get all the properties of the size object, iterates over
    // 'value', 'name' and 'code'. You can inspect everything this way.        
  }
} 
And btw, if you are interested in namespaces, you may want to have a look at my solution for simple but powerful namespace and dependency management for javascript: Packages JS










沒有留言:

張貼留言