javaScript中var变量的作用域
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javaScript中var变量的作用域</title>
</head>
<body>
<h1>javaScript中var变量的作用域</h1>
</body>
<script type="text/javascript">
//后面有时间再写let的知识点,今天先写var的知识点
//案例1
function fn1(){
if(true){
//语句块中声明的变量将成为语句块所在函数的局部变量
//hometown变量的作用域是声明了hometown的这个函数,而不是hometown所在的if语句块
var hometown = '江西省赣州市于都县';
console.log(hometown); //江西省赣州市于都县
}
//hometown变量的作用域是在整个函数
console.log(hometown); //江西省赣州市于都县
}
fn1();
//案例2
//在函数之外声明的变量,叫做全局变量
if(true){
//age变量可以被当前文档中的任何其他代码所访问
//虽然age变量是写在if语句块中的,但是此时age变量的作用域等同于全局变量
var age = 6;
console.log(age); //6
}
//if语句块之外,仍然可以访问到age变量
console.log(age); //6
//案例3
function fn2(){
for (var f = 0; f < 3; f++) {
//*******0
//*******1
//*******2
console.log('*******' + f);
}
//for语句块之外,仍然可以访问到f变量
console.log('--------' + f);//--------3
}
fn2();
//案例4
for (var h = 0; h < 2; h++) {
//*******0
//*******1
console.log('*******' + h);
}
//for语句块之外,仍然可以访问到h变量
console.log('--------' + h); //--------2
</script>
<script type="text/javascript">
//if语句块之外,仍然可以访问到age变量
console.log(age); //6
</script>
</html>
还没有评论,来说两句吧...