[removed] final / immutable global variables?

前端 未结 14 2060
既然无缘
既然无缘 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
    
    0 讨论(0)
  • 2020-12-13 09:35

    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>
    
    0 讨论(0)
提交回复
热议问题