在嵌套函数中,所有子函数都可以访问所有父函数的变量。对变量的任何更改在当前函数的本地范围内以及随后调用的所有嵌套子函数中都是可见的。当子函数执行完毕后,变量将恢复到调用子函数之前的原始值。
为了在所有嵌套函数作用域中应用变量更改,变量作用域类型需要更改为AllScope:
Set-Variable -Name varName -Option AllScope
这样,无论变量在嵌套函数的哪个级别被修改,即使在子函数终止并且父函数将看到新的更新值之后,更改也是持久的。
嵌套函数中变量作用域的正常行为:
function f1 ($f1v1 , $f1v2 )
{
function f2 ()
{
$f2v = 2
$f1v1 = $f2v #local modification visible within this scope and to all its children
f3
"f2 -> f1v2 -- " + $f1v2 #f3's change is not visible here
}
function f3 ()
{
"f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
$f3v = 3
$f1v2 = $f3v #local assignment will not be visible to f2
"f3 -> f1v2 -- " + $f1v2
}
f2
"f1 -> f1v1 -- " + $f1v1 #the changes from f2 are not visible
"f1 -> f1v2 -- " + $f1v2 #the changes from f3 are not visible
}
f1 1 0
打印输出:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 0
f1 -> f1v1 -- 1
f1 -> f1v2 -- 0
带有AllScope 变量的嵌套函数:
function f1($f1v1, $f1v2)
{
Set-Variable -Name f1v1,f1v2 -Option AllScope
function f2()
{
$f2v = 2
$f1v1 = $f2v #modification visible throughout all nested functions
f3
"f2 -> f1v2 -- " + $f1v2 #f3's change is visible here
}
function f3()
{
"f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
$f3v = 3
$f1v2 = $f3v #assignment visible throughout all nested functions
"f3 -> f1v2 -- " + $f1v2
}
f2
"f1 -> f1v1 -- " + $f1v1 #reflects the changes from f2
"f1 -> f1v2 -- " + $f1v2 #reflects the changes from f3
}
f1 1 0
打印输出:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 3
f1 -> f1v1 -- 2
f1 -> f1v2 -- 3