[removed] final / immutable global variables?

前端 未结 14 2095
既然无缘
既然无缘 2020-12-13 09:03

I think I know the answer but... is there any way to prevent a global variable from being modified by later-executing

14条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 09:35

    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
    

提交回复
热议问题