Created
June 10, 2016 14:18
-
-
Save LorisBachert/81ddb35706bfdd6b718ecfabacefaf76 to your computer and use it in GitHub Desktop.
Create a javascript object with frozen constants. Includes a deep freeze aswell!!!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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