【问题标题】:Understand the scope of the variables in Node.js了解 Node.js 中变量的范围
【发布时间】:2012-01-19 10:04:57
【问题描述】:

我有以下 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 值?

【问题讨论】:

    标签: node.js


    【解决方案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
    

    【讨论】:

    • 谢谢你的回答,但我不明白它是否读取全局范围(Test() 函数)或者如果我将它作为参数传递(v, function(){ .. }我可以在不参考全局的情况下使用它吗?因为循环很快结束(6 - 5 - 4 - 3 - 2 - 1)但是当我打印 v 值时它具有先前的值(当我调用 due() 函数时)因此,如果我使用变量作为参数,该变量的值保持不变(作为不同的范围)?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-05-02
    • 2011-04-15
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多