- JavaScript 中没有块作用域,只用函数作用域
1<script type="text/javascript">
2 function rainman(){
3 // rainman函数体内存在三个局部变量 i j k
4 var i = 0;
5 if ( 1 ) {
6 var j = 0;
7 for(var k = 0; k < 3; k++) {
8 alert( k ); //分别弹出 0 1 2
9 }
10 alert( k ); //弹出3
11 }
12 alert( j ); //弹出0
13}
14</script>
15
- let 和 const 关键字支持在块级声明中创建使用局部作用域
其中 let 创建的变量不可重复声明,const 创建的变量其值不可修改
1if (true) {
2 // this 'if' conditional block doesn't create a scope
3
4 // name is in the global scope because of the 'var' keyword
5 var name = 'Hammad';
6 // likes is in the local scope because of the 'let' keyword
7 let likes = 'Coding';
8 // skills is in the local scope because of the 'const' keyword
9 const skills = 'JavaScript and PHP';
10}
11
12console.log(name); // logs 'Hammad'
13console.log(likes); // Uncaught ReferenceError: likes is not defined
14console.log(skills); // Uncaught ReferenceError: skills is not defined - 未使用var、let、const关键字声明的变量都是全局变量
1<script type="text/javascript">
2 function rain(){
3 x = 100; //声明了全局变量x并进行赋值
4}
5rain();
6alert( x ); //会弹出100
7</script>
8 - 全局变量都是window对象的属性
1<script type="text/javascript">
2 var x = 100 ;
3alert( window.x );//弹出100
4alert(x);
5</script>
6 - JavaScript 会率先执行所有的变量声明语句,注意下面代码的理解
1<script type="text/javascript">
2 var x = 1;
3 function rain(){
4 alert( x ); //弹出 'undefined',而不是1
5 var x = 'rain-man';
6 alert( x ); //弹出 'rain-man'
7 }
8 rain();
9</script>
10