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
This would be much cleaner approach
var CONSTANTS = function() {
var constants = { } ; //Initialize Global Space Here
return {
defineConstant: function(name,value)
{
if(constants[name])
{
throw "Redeclaration of constant Not Allowed";
}
},
getValue(name)
{
return constants[name];
}
} ;
}() ;
CONSTANTS.defineConstant('FOO','bar') ;
console.log(CONSTANTS.getValue('FOO')) ; //Returns bar
CONSTANTS.defineConstant('FOO','xyz') ; // throws exception as constant already defined
CONSTANTS.getValue('XYZ') ; //returns undefined
the const keyword?
Object.defineProperty(window, 'CONSTANT_NAME', {value: CONSTANT_VALUE});
// usage
console.log(CONSTANT_NAME);
Object.defineProperty() creates a property with the following default attributes:
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
Defaults to false.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.
writable
true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.
if the "constant" is an object you might additionally want to make it immutable by freezing it. obj =
Object.freeze(obj). have in mind that child-property-objects are not automatically frozen.
yes the const is short for constant or final in some languages. google "javascript variable const" or constant to double i have even tested it myself so
const yourVar = 'your value';
thats what you are looking for.
You might want to try out this jquery plugin. It prevents you to create global objects in javascript :)
Store data
// 'val' can be a string, integer, hash table, array, object
$.secret( 'in', 'secretName', val );
// or a function
$.secret( 'in', 'secretName', function( arg1, arg2, arg3 ){
// do something here
});
Use data; you can even use it in different files.
var lang = $.secret( 'out', 'lang' );
Call out a function
$.secret( 'call', 'secretName', [ arg1, arg2, arg3 ]);
// or
$.secret( 'call', 'secretName', arg );
Clear data
$.secret( 'clear', 'lang' );
source code is on github
I know this question is old, but you could use Object.freeze(yourGlobalObjectHere); I just wrote a blog post about it here.