理解Node.js中变量的范围

时间:2012-01-19 10:04:57

标签: node.js

我有以下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()内)

可以解释我为什么当我调用回调(cb())时,v值是相同的?

做的:

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

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

1 个答案:

答案 0 :(得分:1)

回调cb()是以下函数:function(){ console.log(v) }v取自定义函数时生效的本地环境,因为它不是回调函数的参数(upvalue)。这意味着,第一次调用test()时,它的值为6,第二次为值5等。

您应该为参数指定与全局变量不同的名称,例如:

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

然后你可能会发现差异。

编辑:这与节点完全无关,更多与JavaScript有关(许多编程语言的行为完全相同)。你应该玩它并把回调等等放在一边。

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
相关问题