gpt4 book ai didi

javascript - 需要范围示例的详细信息

转载 作者:行者123 更新时间:2023-12-02 13:43:20 25 4
gpt4 key购买 nike

我正在学习 JS 中的范围,但我陷入了一个示例:

function one() {
var a = 1;
console.log(a);

function two() {
var a = a + 2;
console.log(a);
}

two();

}

one();

运行此命令将输出NAN。你能解释一下为什么它不从函数 one() 中获取变量 a 而是选择定义它再次 ?我知道 var 再次定义了它,但考虑到它是一个嵌套函数,为什么它不使用父级的变量?

谢谢!

更新:

据我所知,如果我错了,请纠正我,相同的变量名可以出现在不同的范围中

 function one() {
var a = 1;
console.log( a );
}
function two() {
var a = 2;
console.log( a );
}
one();
two();

我还知道一个作用域中的代码可以访问该作用域或该作用域之外的任何作用域的变量

 function one() {
var a = 1;
function two() {
var b = 2;
console.log( a + b );
}
two();
console.log( a );
}
one();

这就是我感到困惑的原因

最佳答案

I know that var defines it again, but conidering it's a nested function why it doesn't use the variable from parent?

因为...var 在嵌套作用域中再次定义了它。这意味着 two 中的 aone 中的 a 不同;这是一个不同的变量,阴影(隐藏)onea,所以two不能使用它。

现在我们知道这是一个不同的变量,让我们看看为什么从 twoconsole.log 中得到 NaN:

var a = a + 2;

被这样处理:

var a;
a = a + 2;

并且新声明的没有初始化程序的变量默认值为undefinedundefined + 2NaN

如果我们将 two 更改为 not 影子 atwo 确实可以使用 a:

function one() {
var a = 1;
console.log(a);

function two() {
var b = a + 2; // Note declaring b, and using a
console.log(b);
}

two();
}

one();

关于javascript - 需要范围示例的详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42808876/

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