I think I know the answer but... is there any way to prevent a global variable from being modified by later-executing ? I know global variables ar
what about this code by http://ejohn.org/ @ http://ejohn.org/blog/ecmascript-5-objects-and-properties/
Look like this actually works... I run some "little" testing and freeze the variables and attributes.
Freezing an object is the ultimate form of lock-down. Once an object has been frozen it cannot be unfrozen – nor can it be tampered in any manner. This is the best way to make sure that your objects will stay exactly as you left them, indefinitely.
Object.freeze = function( obj ) {
var props = Object.getOwnPropertyNames( obj );
for ( var i = 0; i < props.length; i++ ) {
var desc = Object.getOwnPropertyDescriptor( obj, props[i] );
if ( "value" in desc ) {
desc.writable = false;
}
desc.configurable = false;
Object.defineProperty( obj, props[i], desc );
}
return Object.preventExtensions( obj );
};
Little example
var config = (function (__name) {
name: __name
var _local = {
Server: "SomeText",
ServerDate: "SomeServerDate",
JSDate : Util.today(),
User : {
user: "1stUser",
name: "",
email: ""
},
}
/*Private Methods*/
function freezing(__array) {
$.each(__array, function (_index, _item) {
Object.freeze(_item);
});
}
/*Public Methods*/
var $r = {};
$r.info = function () {
return _local;
}
freezing([
_local,
_local.User
]);
_local.User.user = "newUser"; //Trying to assing new value
//Remain with the same value as first declaration
console.log(_local.User.user); //--> "1stUser"
return $r;
})("config");