简体   繁体   English

为什么我的全局变量在本地声明之前被遮蔽了?

[英]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(); 

The result of the 3 alerts is: 1 , undefined , 2 (Chrome 25) 3个警报的结果是: 1undefined2 (Chrome 25)

My question is: why the second alert is undefined? 我的问题是:为什么第二个警报未定义? Why not 1? 为什么不是1? Isn't there a global variable x? 是不是有全局变量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. 在函数y()的开头,声明了局部变量x但未初始化。

The variable declaration in the function is hoisted to the top. 函数中的变量声明被提升到顶部。 So it technically looks like this: 所以它在技术上看起来像这样:

var y = function() {
    var x;

    alert(x);

    x = 2;
};

The local variable overshadows the global one. 局部变量掩盖了全局变量。 That is why the alert returns undefined . 这就是警报返回undefined

Since scope in JavaScript is a function object. 因为JavaScript中的范围是一个函数对象。 When you execute some code in a function(your code sample), "alert(x)" will find if there's any definition of "x" in the function. 当您在函数(代码示例)中执行某些代码时,“alert(x)”将查找函数中是否存在“x”的任何定义。 So, there's a "var x = 2" in this function. 所以,这个函数中有一个“var x = 2”。 But the JavaScript runtime will explain your code like this: 但是JavaScript运行时会像这样解释你的代码:

x = 1; 
alert(x); 
var y = function() { 
  var x;
  alert(x); 
  x = 2; 
  alert(x); 
} 
y(); 

So, the x in the second alert is "undefined" not "1". 因此,第二个警报中的x是“未定义”而不是“1”。 So when you declare some variable in a function, I recommend you to declare the variables in the top of your function. 因此,当您在函数中声明某个变量时,我建议您在函数顶部声明变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM