muntasir
muntasir

Reputation: 11

Global Variable JavaScript (Changing Value)

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>

Upvotes: 1

Views: 33595

Answers (3)

wong ka chun
wong ka chun

Reputation: 71

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!

Upvotes: 2

wong ka chun
wong ka chun

Reputation: 71

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

Upvotes: 5

outis
outis

Reputation: 77400

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.

Upvotes: 7

Related Questions