您的位置:首页 > Web前端 > JavaScript

[JavaScript] Script 中 function, variable 的定义会提升到函数执行前面;但是,function 中定义的 global variable 则不会被提升

2011-09-10 11:34 555 查看
1、Script 中 function, variable 的定义 会提升到函数执行前面

2、但是,function 定义的 global variable 则不会被提升

<html>
	<head>
		<script type="text/javascript">			
			function demoForIn(){
				//只有此 function 被调用时,glbInFunction 才会被定义到 global scope 中
				glbInFunction = "I'm a global variable, and I'm defined in a function";
				var obj = {'a':123, b:456};//注意:a 是用 JavaScript identifier,而 b 是一个字符串
				//当然,即使这样,我们在 typeof tmpName 时,得到的都是 string
				for(tmpName in obj){// 调用此方法时,会使得 global scope 中 定义一个 tmpName
					alert(typeof tmpName);//string
					alert(tmpName);//注意:tmpName仅仅是属性的名字(是个字符串)
					alert(obj[tmpName]);// for/in时正确的遍历方法
					alert(obj.tmpName);//无法通过此方法调用(不会报错,但是得到的值是 undefined)
				}
			}
			
			function main(){
				// 注释掉后:执行时会报错,因为 glbInFunction, tmpName 未定义
				// 保留此句,则 glbInFunction 就是 demoForIn()定义的值;tmpName为 b
				demoForIn();
				alert(glbInScript);
				alert(glbInFunction);
				alert(tmpName)
			}
			var glbInScript="I'm a global variable, and I'm defined in script";
			
		</script>
	</head>

	<body>
		<form>
			<input type="button" name="demojavascript" value="Demo for/in" 
							onclick="main();"/>
		</form>
	</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐