I think I know the answer but... is there any way to prevent a global variable from being modified by later-executing <script>
? I know global variables are bad in the first place, but when necessary, is there a way to make it "final" or "immutable"? Hacks / creative solutions are welcome. Thanks
views:
1509answers:
9Not that I know of. The best I can think of is storing the value on an object that won't likely be modified.
e.g.
navigator.pleaseDontChangeThis = 25;
It can still be changed, but most normal JS will have no need to set/change any values on the navigator object. I personally use this to store a unique generated ID. ;-)
Conventions and good Documentation.
You can prefix your "immutable" variable with two (or more) underscores to indicate that is something not meant to be used by others and to avoid other people's variables clashing with yours.
Maybe creating a 'namespace' like __GLOBALNAMESPACE (Ugly name, I know) and then adding your variables into it (eg __GLOBALNAMESPACE.my_var) and creating a method like this one to retrieve them:
getVariable(string name){ return __GLOBALNAMESPACE[name] }
Just my 2 cents. Regards.
You can use closure technique, MYGLOBALS is an object that has a function called getValue against the "globals" associative array that is out of scope for everything except MYGLOBALS instance.
var MYGLOBALS = function() {
var globals = {
foo : "bar",
batz : "blah"
}
return { getValue : function(s) {
return globals[s];
}
}
}();
print(MYGLOBALS.getValue("foo")); // returns "bar"
print(MYGLOBALS.getValue("notthere")); // returns undefined
MYGLOBALS.globals["batz"] = 'hardeehar'; // this will throw an exception as it should
Choose a variable name which is unlikely to be overwritten by accident and trust the programmer to not do stupid things. JavaScript is not Java, so don't pretend it was.
Also, if what you really want to do is namespacing, use a self-executing function literal:
var myLibName = (function() {
var aPrivateVar;
function aPrivateFunction() {}
function accessorForPrivateVar() {
return aPrivateVar;
}
// public interface:
return {
getPrivateVar : accessorForPrivateVar
}
})();
try this:
const whatEver = 'Hello World!!!';
function foo(value){
whatEver = value;
}
then you would call it like so...
<div onclick="foo('New Value');">Change Me First</div>
<div onclick="alert(whatEver);">Then click me After: Should Be alert "Hello World!!!"</div>
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.