Skip to content

Instantly share code, notes, and snippets.

@LorisBachert
Created June 10, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LorisBachert/81ddb35706bfdd6b718ecfabacefaf76 to your computer and use it in GitHub Desktop.
Save LorisBachert/81ddb35706bfdd6b718ecfabacefaf76 to your computer and use it in GitHub Desktop.
Create a javascript object with frozen constants. Includes a deep freeze aswell!!!
// Define your constants
var Constants = {
"CONSTANT_NAME" : "CONSTANT_VALUE",
"CONSTANT_OBJECT" : {
"CONSTANT_OBJECT_KEY" : "CONSTANT_OBJECT_VALUE"
}
};
createConstantsAndFreeze(Constants);
// Do the magic
function createConstantsAndFreeze(obj) {
var keys = Object.keys(obj);
keys.forEach(function(property) {
var value = obj[property];
// Create Read-Only property
Object.defineProperty(obj, property, {
value: value,
enumerable: true
});
if (value instanceof Object) {
// Do some recursive stuff
createConstantsAndFreeze(value);
}
});
// freeze
Object.freeze(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment