gpt4 book ai didi

node.js - 了解 Node.js 中变量的范围

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:52 24 4
gpt4 key购买 nike

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

最佳答案

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

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

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

然后您可能会发现差异。

编辑:这与 Node 根本无关,更多的是与 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

关于node.js - 了解 Node.js 中变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8924155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com