现在的位置: 首页 > 综合 > 正文

js没有块级作用域

2018年05月20日 ⁄ 综合 ⁄ 共 502字 ⁄ 字号 评论关闭
<html>
<head>
<script type="text/javascript">
    function test(o) {
		var i = 0;
		if (typeof o == "object") {
			var j = 0;
			for (var k = 0; k < 10; k++) 
			{
				document.write(k);
			}
			document.write(k);  //还可以访问到k为10
		}
		document.write(j); //还可以访问到j为0
	}
	var o = new Object();
	test(o);
</script>
</head>
</html>

<html>
<head>
<script type="text/javascript">
   var scope = "global";
   function f() {
	   alert(scope);  //显示undefined
	   var scope = "local";
	   alert(scope);
   }
   f();
</script>
</head>
</html>

对第一个alert()显示的是undefined,没有显示global,因为语句var scope="local"限制了变量scope的作用范围,scope变量

为局部变量,全局变量scope在函数内部不可见。

抱歉!评论已关闭.