JavaScript Variable Area

I declared var1 inside the function. However, when I try to assign a value to inner_function2, it seems that another var1 is created instead of referencing the first.

var func1 = function(response) {

    var var1;

    function inner_function2(param) {

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

}()
+3
source share
2 answers

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

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!

+4
source

successthe callback Ext.Ajax.requestis called after an AJAX request. This means that the called function (as func1()it inner_function2()has already returned, and their area has been deleted.

Let's try to show the sequence of events

  • func1() called
  • Local variable var1declared
  • inner_function2() ( , )
  • Ext.Ajax.request(), success
  • inner_function2() - AJAX
  • func1() , var1 ( ) - AJAX
  • AJAX - success. var1 , a (. , ). var1 - , , .

, "A" AJAX "".

+4

Source: https://habr.com/ru/post/1781595/


All Articles