0

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?

1
  • What isn't clear from my initial post is that the value of foo set within the getJSON method will be used in later functions, which is why the variable is initialized outside of the getJSON method, though clearly there is a subtly of JavaScript that needs to be cleared up. Commented Apr 7, 2010 at 19:41

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.