开发者

Variable scoping and the jQuery.getJSON() method

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

  开发者_Python百科      alert(foo); // undefined
    }
}

someObject.someMethod();

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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜