Unagi
Unagi

Reputation: 105

Javascript variable scope question

I am confused with the variable scope in Javascript. I am trying to load data file (.json) using Prototype library and parse the response text using json-sans-eval. The problem is it seems to me that the content from data file is lost if I tried to access "dataObj" outside of the Ajax.Request scope.

The variable in Javascript has reference count. I don't understand how can the global variable 'dataObj' will lose its data. Any hint or help?

Thank you!

var dataObj;
function OnLoadHandle() {
    new Ajax.Request('data.json',
    {
        method:'get',
        onSuccess: function(transport)
        {
            var response = transport.responseText || "no response text";
            dataObj = jsonParse(response);
            console.log(dataObj["[0,0]"]); // OK
        },
        onFailure: function(){ alert('Something went wrong...') }
    });
    console.log(dataObj["[0,0]"]); // ERROR 
}

Upvotes: 1

Views: 547

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 185872

The second invocation of console.log(...) at the end of OnLoadHandle runs immediately, whereas the one inside onSuccess runs only after the request completes. The second console.log serves no purpose.

More broadly, this means that there is no point in making dataObj a global variable. It is only useful after it is assigned in onSuccess and should therefore be scoped as a local variable within onSuccess. If you need it elsewhere, onSuccess should pass it as a parameter to some other function.

Upvotes: 6

Related Questions