【发布时间】:2023-03-28 22:45:01
【问题描述】:
如果我调用一个传递参数param的函数A,其中调用了一个异步函数B,那么异步函数B的回调C是否能够使用给函数A的参数param?如果是,如果在函数 B 开始和回调 C 被调用之间的时间内我重新调用函数 A,这会改变吗?
例子:
function A(param) {
value1 = param;
doc = "hello";
//this is the async function B;
database.insert(doc, function() {
//this is the invoked callback C when the async function is solved.
console.log(value1)
//can i log value1? yes. if yes, will this change if i re-invoke
//function A before the callback is invoked or two different processes will start?
})
}
A('hello');
A('not hello');
想知道如果在上一次调用的回调函数之前第二次调用一个函数,是否会在控制台上打印正确的值:
你好; 不是你好;
永远不会 不是你好; 不是你好;
因为第二次的调用会感染第一次。
【问题讨论】:
-
用
var声明你的局部变量。 -
先谢谢你。这是正确工作所需要的还是只是建议? @Pointy
-
这只是一个非常重要的习惯,也是一个需要理解的重要概念。
-
好的,非常感谢您的建议。但这不是我要问的! :)
标签: javascript asynchronous callback scope parameter-passing