为什么我的全局变量在本地声明之前被映射? [英] Why is my global variable shadowed before the local declaration?
本文介绍了为什么我的全局变量在本地声明之前被映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
x = 1;
alert(x);
var y = function(){
alert(x);
var x = 2;
alert(x);
}
y();
3个警报的结果是: 1
, undefined
, 2
(Chrome 25)
我的问题是:为什么第二个警报是未定义的?为什么不是1?是不是有一个全局变量x?
解决方案
由于手段,这是执行的内容:
x = 1;
alert(x);
var y = function(){
var x; //< - 从原来的位置吊起来。
alert(x);
x = 2;
alert(x);
}
y();
在函数 y()
,局部变量 x
被声明但未被初始化。
x = 1;
alert(x);
var y = function() {
alert(x);
var x = 2;
alert(x);
}
y();
The result of the 3 alerts is: 1
, undefined
, 2
(Chrome 25)
My question is: why the second alert is undefined? Why not 1? Isn't there a global variable x?
解决方案
Due to hoisting, this is what gets executed:
x = 1;
alert(x);
var y = function() {
var x; // <-- this gets hoisted up from where it was.
alert(x);
x = 2;
alert(x);
}
y();
At the start of function y()
, the local variable x
is declared but not initialized.
这篇关于为什么我的全局变量在本地声明之前被映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文