gpt4 book ai didi

javascript - 函数范围javascript之间的变量差异

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:36 26 4
gpt4 key购买 nike

我正在阅读有关 javascript 的执行上下文和范围的主题。下面是一个简单的代码:

 var scope="global";  
function t(){
alert(scope); // alert :"undefined"
var scope="local" ;
alert(scope); // alert: "local"
}
t();

如果我删除 'var scope="local"; ',它会变成这样:

var scope="global";  
function t(){
alert(scope); // alert :"global"
}
t();

我不明白为什么在我删除函数 t() 中的 var scope="local" 后,scope 的值在第二种情况下更改为“global”。

谁能帮忙解释一下,谢谢!

最佳答案

当你这样做时:

scope = 'global'
function t() {
alert(scope) // undefined
var scope = 'func'
alert(scope) // func
}
t()

var scope... 行,您告诉 js:注意,我在这个函数中定义了“作用域”。所以 JS 重置它的值(未定义)。就像你这样做一样:

scope = 'global'
function t() {
var scope; // erase previous 'scope', so it is now undefined
alert(scope) // undefined
scope = 'func'
alert(scope) // func
}
t()

但如果你只是这样做

scope = 'global'
function t() {
alert(scope) // global
}
t()

你没有在你的函数中创建变量 scope ,所以 JS 不会删除它的值,当你尝试访问它时,JS 试图找到它更高的位置(在全局命名空间中这种情况)

希望你明白了......这确实有点奇怪,因为首先,JS 会查找你在函数中声明的每个变量(并重置/初始化它们),然后然后运行你的函数。

马特

关于javascript - 函数范围javascript之间的变量差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40054456/

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