JavaScript 中全局和局部变量的奇怪行为 [英] Strange Behavior on Global and Local Variable in JavaScript
本文介绍了JavaScript 中全局和局部变量的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了以下代码:
var a = 5;
function x() {
console.log(a);
}
x();
它按预期运行并打印 5.
It runs as expected and prints 5.
但我更改了代码,因此全局变量 a 将被覆盖如下:
But i changed the code so the global variable a will be overwrite as follows:
var a = 5;
function x() {
console.log(a);
var a = 1;
}
x();
它打印未定义.这对我来说没有意义,因为覆盖应该在 console.log(a) 之后发生.那么问题出在哪里?
It prints undefined. It doesn't make sense for me since the overwrite should be happened right after console.log(a). So what is the problem?
推荐答案
发生这种情况是因为您的第二个 a
变量被提升"到函数的顶部并且它隐藏了第一个 >a
.实际发生的事情是这样的:
This is happening because your second a
variable is being 'hoisted' to the top of the function and it hides the first a
. What is actually happening is this:
var a = 5;
function x() {
var a;
console.log(a);
a = 1;
}
x();
这是一篇关于从足够好的提升提升的文章,以进一步阅读该主题.
Here is an article on hoisting from adequately good for further reading on the subject.
这篇关于JavaScript 中全局和局部变量的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文