javascript——变量闭包1

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>js01_hello</title>
	<meta name="author" content="Administrator" />
	<script type="text/javascript">
	function fn1() {
		//创建了一个数组
		var fns = new Array();
		//i这个变量是保存在fn1这个作用域中的
		for(var i=0;i<10;i++) {
			//数组中方的值是一组函数
			fns[i] = function() {
				return i;
			}
		}
		return fns;
	}
	
	var fs = fn1();
	for(var i=0;i<fs.length;i++) {
		//此时通过闭包来调用所有函数,当输出i的时候会去上一级的作用域中查找
		//这个时候i的值已经10,所以连续输出了10个10
		document.write(fs[i]()+"<br/>");
	}
	</script>
</head>
<body>
</body>
</html>

  

posted on 2015-02-11 12:53  aicpcode  阅读(147)  评论(0编辑  收藏  举报

导航