最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

extjs - JavaScript variable scope - Stack Overflow

programmeradmin1浏览0评论

I have declared var1 inside the function. However, when i try to assign a value in inner_function2, it seems another var1 is create instead of referencing to the first one.

var func1 = function(response) {

    var var1;

    function inner_function2(param) {

        Ext.Ajax.request({
            url:'',
            params: param,
            success:function(result, request) { 
                var1 = a;
                }
            });
    }   

}()

I have declared var1 inside the function. However, when i try to assign a value in inner_function2, it seems another var1 is create instead of referencing to the first one.

var func1 = function(response) {

    var var1;

    function inner_function2(param) {

        Ext.Ajax.request({
            url:'',
            params: param,
            success:function(result, request) { 
                var1 = a;
                }
            });
    }   

}()
Share Improve this question edited Dec 22, 2010 at 8:30 Ionuț G. Stan 179k19 gold badges195 silver badges204 bronze badges asked Dec 22, 2010 at 6:15 Progress ProgrammerProgress Programmer 7,39415 gold badges51 silver badges55 bronze badges 1
  • I suppose the invalid syntax if a copy+paste issue? Also, how do you determine that "it seems another var is created"? – deceze Commented Dec 22, 2010 at 6:21
Add a ment  | 

2 Answers 2

Reset to default 4

success callback of Ext.Ajax.request is called after AJAX request has been returned. This means, the function that called it (both func1() and inner_function2() have already returned, and their scope was deleted.

Let's try to show a sequence of events

  1. func1() is called
  2. local variable var1 is declared
  3. inner_function2() is called (I'm assuming you do call it somewhere)
  4. Ext.Ajax.request() is called, with success callback declared
  5. inner_function2() ends - the AJAX request is running in the background
  6. func1() ends, local variable var1 is deleted (it still is available in callback scope though)- the AJAX request is running in the background
  7. AJAX request finishes - success callback is called. Since there is no local variable var1 a global variable is created and assigned value of a (see the ments below why this is deleted). Local variable var1 is still available in callback's scope, but once the callback ends, the variable is no longer available anywhere, so you can't use it.

Remember that 'A' in AJAX stands for 'Asynchronous'.

I suggest you specify the scope explicitly in your code. you can do like:

var func1 = function(response) {
  var var1;
  var outer_scope = this;

  function inner_func2(param) {
    Ext.Ajax.request({
      url: '',
      params: param,
      scope: outer_scope,
      success: function(result, request) {
        var1 = a;
      }
    });
  }
}()

Hope it works!

发布评论

评论列表(0)

  1. 暂无评论