views:

78

answers:

2

The jQuery.getJSON() method seems to ignore the normal rules of scoping within JavaScript.

Given code such as this...

someObject = {
    someMethod: function(){
        var foo;

        $.getJSON('http://www.somewhere.com/some_resource', function(data){
            foo = data.bar;
        });

        alert(foo); // undefined
    }
}

someObject.someMethod();

Is there a best practice for accessing the value of the variable outside of the getJSON scope?

+2  A: 

The problem with your code is that foo is being set AFTER the JSON request has come back (in the callback function). Moving the alert into the callback would solve the problem.

Scope-wise, the code is fine. Because javascript has closures, the callback function will have access to the surrounding context (including the foo variable). So when you are setting foo, you are setting the same variable.

Ben
A: 

This is not about some weird specialty of getJSON(). It's perfectly normal JS behaviour - you are working with a callback function after all. Callbacks that run completely detached and separately from the context they have been defined in.

Best is you handle everything right in the callback:

someObject = {
  someMethod: function(){
    $.getJSON('http://www.somewhere.com/some_resource', function(data) {
      var foo = data.bar;
      alert(foo);
    });
  }
}
Tomalak