JS 变量提升

1 var a = 1;
2   function foo() {
3     console.log(a);
4     var a = 2;
5     
6   }
7 
8   foo();  //undefined

根据变量提升机制,最后得出undefined;

变量提升是指在一个作用域中声明的变量,JS解析时会把变量声明提升至作用域内的第一行,也就是说上面那段代码等同于:

1     var a = 1;
2     function foo() {
3         var a;  //被提升至作用域内第一行
4         console.log(a);
5         var a = 2;
6     
7   }
8 
9   foo();

因此,也就可以理解为什么是undefined了

原文地址:https://www.cnblogs.com/samtrybest/p/5097090.html