JavaScript 变量作用域
我已经在函数内声明了 var1 。然而,当我尝试在inner_function2中分配一个值时,似乎创建了另一个var1而不是引用第一个。
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;
}
});
}
}()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AJAX 请求返回后,会调用
Ext.Ajax.request
的success
回调。这意味着调用它的函数(func1()
和inner_function2()
都已返回,并且它们的作用域已被删除。让我们尝试显示一系列事件
var1
被声明inner_function2()
被调用(我假设你确实在某个地方调用了它)Ext调用 .Ajax.request()
,并声明success
回调inner_function2()
结束 - AJAX 请求在后台运行func1()
结束,局部变量var1
被删除(尽管它在回调作用域中仍然可用) - AJAX 请求在后台运行success
回调由于没有局部变量(请参阅下面的注释,了解为什么要删除它) ). 局部变量var1
,因此创建了一个全局变量并为其分配了值a
var1
在回调的作用域中仍然可用,但是一旦回调结束,该变量就不再在任何地方可用,因此您无法使用它。请记住,AJAX 中的“A”代表“异步”。
success
callback ofExt.Ajax.request
is called after AJAX request has been returned. This means, the function that called it (bothfunc1()
andinner_function2()
have already returned, and their scope was deleted.Let's try to show a sequence of events
func1()
is calledvar1
is declaredinner_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 backgroundsuccess
callback is called.Since there is no local variable(see the comments 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:
Hope it works!