Javascript: final / immutable global variables?

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


Solution 1:

the const keyword?

Solution 2:

I know this question is old, but you could use Object.freeze(yourGlobalObjectHere); I just wrote a blog post about it here.

Solution 3:

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];
        }
    }
}();
alert(MYGLOBALS.getValue("foo"));  // returns "bar"
alert(MYGLOBALS.getValue("notthere")); // returns undefined
MYGLOBALS.globals["batz"] = 'hardeehar'; // this will throw an exception as it should