views:

200

answers:

4

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>
+4  A: 

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.

outis
A: 

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

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");
            }
        }   
    }

muntasir
SO is a Q add an extra four spaces to each line of code when posting.
outis
outis