Skip to content

Instantly share code, notes, and snippets.

@tal
Last active August 29, 2015 14:00
Show Gist options
  • Save tal/11190805 to your computer and use it in GitHub Desktop.
Save tal/11190805 to your computer and use it in GitHub Desktop.
_prepare_environment: function _prepare_environment() {
var env = this.options.env || {};
delete this.options.env;
this.env = _.bind(function() {
return _.clone(env);
});
},
_prepare_environment: function _prepare_environment() {
var env = this.options.env || {};
delete this.options.env;
deepFreeze(env);
Object.defineProperty(this, 'env', {
value: env,
writeable: false,
enumerable: true,
configurable: false
});
},
/**
* Performs a deep (recursive) freeze on the object preventing
* not only the object from being modified, but any decending
* properties as well.
*
* Source (4/22/2014):
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#Examples
*
* Browser Compatibility
*
* IE9+, Fx 4+, Chr 6+, Saf 5.1+
*
* @param {Object} o
*/
function deepFreeze(o) {
var prop, propKey;
Object.freeze(o); // First freeze the object.
for (propKey in o) {
prop = o[propKey];
if (!o.hasOwnProperty(propKey) || !(typeof prop === "object") || Object.isFrozen(prop)) {
// If the object is on the prototype, not an object, or is already frozen,
// skip it. Note that this might leave an unfrozen reference somewhere in the
// object if there is an already frozen object containing an unfrozen object.
continue;
}
deepFreeze(prop); // Recursively call deepFreeze.
}
}
/**
* Defines a property on an object and makes it immutable such that
* it, or its descending objets cannot be changed in any way.
* The object can still be deleted
*
* @param {Object} obj Object on which to add the property
* @param {String} name Name of property
* @param {Object} value Value to set the property to
*/
function defineImmutableProperty(obj, name, value) {
deepFreeze(env);
Object.defineProperty(obj, name, {
value: value,
writeable: false,
enumerable: true,
configurable: true
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment