So, I was inspired by this question ( Enums in JavaScript? ) to get to work on a library insert for JavaScript to enable unmodifiable Enumerations. I have a decently working method defined already, but I'd like to flesh it out more.
This concept makes use of Object.defineProperty
(Documentation: Here)
My current definition allows for :
var obj1 = {}, obj2 = {}, obj3 = {};
// Straight declaration (normal)
obj1.Enum('RED','BLUE','GREEN');
obj1.RED // == 0
obj1.BLUE // == 1
obj1.GREEN // == 2
// Buffer (padding) usage
obj2.Enum('RED','BLUE',null,undefined,'','GREEN');
obj2.RED // == 0
obj2.BLUE // == 1
obj2.GREEN // == 5
// Direct offset and case-correction
obj3.Enum('RED','BLUE',10,'gReEn','burnt orange');
obj3.RED // == 0
obj3.BLUE // == 1
obj3.GREEN // == 11
obj3.BURNT_ORANGE // == 12
What I have so far:
var odp=Object.defineProperty;
odp(Object.prototype,'Enum', {
value: function() {
var ignore=[undefined,null,''], n=0, args=arguments;
for(var i in args) {
if(ignore.indexOf(args[i])<0) {
if( typeof args[i]=="number") {
n=parseInt(args[i]);
} else {
try {
odp(this,String(args[i]).toUpperCase().replace(" ","_"), {
value:parseInt(n),enumerable:true
});
} catch(e) {
console.warn(e.message);
n--;
}
}
}
n++;
}
return this;
}
});
2 things I'd like to add to this are:
- Older browser support: So, redefining
Object.defineProperty
where it's not defined. (I don't currently have access to the older browsers to test possible re-definitions) - Any considerations I may have missed it the Enum definition.
jsFiddle :
- Version 4: http://jsfiddle.net/rqYgt/4/
- Version 5: http://jsfiddle.net/rqYgt/5/
Note: The reason I have odp=Object.defineProperty
and args=arguments
is that I run my JavaScript through a closure compiler before inserting it into my pages, doing this assists with compression. (for those that may be wondering)