[英]Passing a variable into a function within a function
I trying to pass a variable down one level into a setInterval function my code looks something like this: 我试图将一个变量向下传递到setInterval函数中,我的代码如下所示:
function file_copy_progress(directory){
console.log("stage 1 " + directory);
setInterval(function(directory){
console.log("stage 2 " + directory);
}, 1000);
}
then I call it like this: 然后我这样称呼它:
file_copy_progress("/home/user/tmp/test");
The result in the console is: 控制台中的结果是:
stage 1 /home/user/tmp/test
stage 2 undefined
stage 2 undefined
stage 2 undefined
...
How would I pass the directory
variable down one more level to be available in the setIntervall function? 如何将
directory
变量再向下传递一个以在setIntervall函数中可用?
Just remove the formal parameter directory
in your inner function 只需删除内部函数中的形式参数
directory
function file_copy_progress(directory){
console.log("stage 1 " + directory);
setInterval(function(){
console.log("stage 2 " + directory);
}, 1000);
}
The directory
parameter of the outer function is captured in the closure of the inner function. 外部函数的
directory
参数在内部函数的闭包中捕获。 Therefore you don't need to pass it as a parameter to the inner function. 因此,您无需将其作为参数传递给内部函数。 On the contrary, if you have the formal parameter to the inner function, it hides the captured variable and makes it inaccessible to the inner function.
相反,如果你有内部函数的形式参数,它会隐藏捕获的变量并使内部函数无法访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.