Object.defineProperty is what you want.
For Example:
var obj = {};
Object.defineProperty(obj, 'key', {
enumerable: false,
configurable: false,
writable: false,
value: 'static'
});
Wil define "obj.key" with value : "static" and it will be readonly.
- Enumerable means that it will show up (or not) when enumerating properties of an object.
- Writable means if you want it to be readonly, you'd say false. not writable.
- Configurable to false if you don't want it to be deletable from the object.
In essence, by putting them all to false, you are creating constants on the object. Btw, their defaults is to be at false.
So effectively doing this:
Object.defineProperty(obj, 'property', { value: 'value'});
Will create a constant on the 'obj' called 'property' with value 'value'. Or you could do this
function setConstant(obj, key, value)
{
Object.defineProperty(obj, key, {value: value });
}
var obj = {};
setConstant(obj, "constantName", "constantValue");
Would make it very readable.