我正在学习 JavaScript 全局变量和局部变量,但我对这个特定函数感到困惑。
var text = "top";
function print() {
return (text);
}
print();
// Returns 'top'
我明白为什么它会返回顶部。 var text
是一个全局变量。 print()
函数可以访问它并返回 text
,从而返回 'top'
。
var text = "top";
function print() {
return (text);
var text = "bottom";
}
print();
// Returns undefined
我对全局变量和局部变量有基本的了解(或者我是这么认为的)。我知道 print
函数可以访问它自己的局部变量和全局变量。
我不明白为什么会返回 undefined
。据我了解,return text;
行检索它有权访问的全局变量 text
(如第一个代码块所示)。返回text = 'top'
后,还声明了自己的同名不同值的局部变量'bottom'
。据我所知,局部变量 bottom
应该放在那里,因为它之前没有被调用。
为什么不显示top
(甚至显示bottom
),而是显示undefined
?
最佳答案
JavaScript hoists您的变量声明使得您的代码在功能上如下:
var text = "top";
function print() {
var text;
return (text);
// Unreachable code below
text = "bottom";
}
print();
// Returns undefined
因为在您的函数中声明的 text
在您点击 return(text)
时尚未定义,并且 text="bottom"
无法访问,print()
返回 undefined
。
参见 What is the scope of variables in JavaScript? 更多。本题涉及案例7。
关于javascript - JavaScript 函数中的局部变量和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005685/