I have a question when I do the node.js async coding.
Here is the example codes:
function foo(arg) {
var a = arg;
console.log(a + ' start');
setTimeout(function () {console.log(a);}, 500);
};
foo(1);
foo(2);
It outputs:
1 start
2 start
1
2
I’m confused. I thought it should output↓, because the local variable is changed by the foo(2)
1 start
2 start
2
2
Could you guys please tell me why/how node.js keep the local variable for the internal callback function access?
Thanks a lot!
Because it is a local variable, not a global. That’s the point of local variables.
var acreates a variable that exists for the life time of the function call. Declaring a function inside it extends the lifetime to cover that function too. When the anonymous function is called it continues to use theathat exists in the scope that it was created in.Since you call the outer function twice, you have two
as. One for each call. You have two anonymous functions, one for each call. Each anonymous function was created in the same scope as one of theas.