LorisBachert
6/10/2016 - 2:18 PM

Create a javascript object with frozen constants. Includes a deep freeze aswell!!!

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);
}