[英]Understand the scope of the variables in 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
值?
回調cb()
是以下函數: function(){ console.log(v) }
,並且v
取自定義函數時有效的本地環境,因為它不是回調函數的參數(高值)。 這意味着,第一次調用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.