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
2 Answers
Reset to default 4success
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
func1()
is called- local variable
var1
is declared inner_function2()
is called (I'm assuming you do call it somewhere)Ext.Ajax.request()
is called, withsuccess
callback declaredinner_function2()
ends - the AJAX request is running in the backgroundfunc1()
ends, local variablevar1
is deleted (it still is available in callback scope though)- the AJAX request is running in the background- AJAX request finishes -
success
callback is called.Since there is no local variable(see the ments below why this is deleted). Local variablevar1
a global variable is created and assigned value ofa
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!