Global Variable JavaScript (Changing Value)

33,417

Solution 1

You can change the value of any variable in JS, local or global. In a function, make sure you don't declare a local variable with the same name and you can access the global. Even if you do declare a local, you can access the global as a property of window. You can change most properties as well; there are very few immutable data types in JS or the DOM.

If a variable isn't being set as you expect, you can use Firefox and firebug to debug the code and observe what's happening.

Solution 2

Please use window['dom1'] = xxx; instead of var dom1 = xxx;

Solution 3

Please try:

<script type="text\javascript"> 
    var dom1 = 3; 

    function work() 
    { 
        ... 
        http.onreadyStateChange=handleHttpResponse; 
        ... 
    } 

    function handleHttpResponse() 
    { 
        var xd; 
        if (http.readyState == 4) 
        { 
            if (http.status == 200) 
            { 
                if (http.responseText == "granted") 
                { 
                    *window['dom1']* = 1; 
                } 
                else 
                { 
                    *window['dom1']* = 2; 
                } 
            } 
            else 
            { 
                alert("Error"); 
            } 
        } 
    } 
</script>

You would find the global value "dom1" is finally changed!

Share:
33,417
muntasir
Author by

muntasir

Updated on July 09, 2022

Comments

  • muntasir
    muntasir almost 2 years

    Is it possible to change the value of a global variable in JavaScript?

    If so, is it possible to do it in a function called by an event listener such as "onreadyStateChange"?

    It's working for normal functions. but doesn't change when I call a function like this:

    <script.......>
        var dom1 = 3;
    
        function work()
        {
            ...
            http.onreadyStateChange=handleHttpResponse;
            ...
        }
    
        function handleHttpResponse()
        {
            var xd;
            if (http.readyState == 4)
            {
                if (http.status == 200)
                {
                    if (http.responseText == "granted")
                    {
                        dom1 = 1;
                    }
                    else
                    {
                        dom1 = 2;
                    }
                }
                else
                {
                    alert("Error");
                }
            }
        }
    </script>
    
    • Christian C. Salvadó
      Christian C. Salvadó about 14 years
      I always try to be cautious when introducing global variables to avoid conflicts with existing or future code, what are you trying to do?