了解Node.js中variables的范围

我有以下的NODE.JS代码:

var a = [1,2,3,4,5,6] function test(){ var v = a.pop() if (!v) return function uno(){ due(v, function(){ console.log(v) }) console.log("Start:",v) return test() } function due(v, cb){ setTimeout(function(){ console.log(v); cb(); }, 5000); } uno(); } test() 

这是输出:

 Start: 6 Start: 5 Start: 4 Start: 3 Start: 2 Start: 1 6 6 5 5 4 4 3 3 2 2 1 1 

正如你可以看到里面的uno()函数我调用due()函数与超时。

我有两个:console.log(v)(在uno()due()

可能somone解释我为什么当我调用callback( cb() )v值是一样的?

这样做的:

 due(v, function(){ console.log(v) }) 

console.log会保持我传递给due()调用的v值? 为什么它没有得到test()函数的“全局” v值?

callbackcb()是以下函数: function(){ console.log(v) }并且v是从定义该函数时有效的本地环境中获取的,因为它不是callback函数的参数(的upvalue)。 也就是说,第一次调用test() ,它的值是6,第二次是值5

您应该给这些参数的名称不同于全局variables,例如:

  function due(param_v, cb){ setTimeout(function(){ console.log(param_v); cb(); }, 500); } 

那么你可能会发现差异。

编辑:这根本不涉及节点,更多的JavaScript(和许多编程语言performance完全一样)。 你应该玩弄它,把callback等放在一边。

 var a function print_a () { // this function sees the variable named a in the "upper" scope, because // none is defined here. console.log(a) } function print_b () { // there is no variable named "b" in the upper scope and none defined here, // so this gives an error console.log(b) } a = 1 print_a() // prints 1 // print_b() // error - b is not defined var c = 1 function dummy () { var c = 99 function print_c () { // the definition of c where c is 99 hides the def where c is 1 console.log(c) } print_c() } dummy() // prints 99