简体   繁体   中英

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:

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?

Just remove the formal parameter directory in your inner function

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM