天天看点

JavaScript执行环境和执行环境对象

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>执行环境和执行环境对象</title>
		<script type="text/javascript">
			/*
			 *	执行环境对象	第一轮
			 * */
			//当outer()调用时,创建一个新的执行对象
//			{
//				
//			}
			outer(1)
			//声明参数并赋值
//			{
//				arg: 1
//			}
			function outer( arg ) {
				//声明局部变量,但没有赋值
//				{
//					arg: 1,
//					local_var: undefined
//				}
				var local_var = 'foo'
				//声明函数并赋值,但并不执行
//				{
//					arg: 1,
//					local_var: undefined,
//					inner: function() {
//						console.log('inner')
//					}
//				}
				function inner() {
					console.log('inner')
				}
				inner()
			}
			
			
			
		</script>
	</head>
	<body>
		
	</body>
</html>
           

执行阶段

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>执行环境对象 第二轮</title>
		<script type="text/javascript">
			/*
			 *	执行环境对象	第二轮
			 * */
			
//				{
//					arg: 1,
//					local_var: undefined,
//					inner: function() {
//						console.log('inner')
//					}
//				}			
			outer(1)
			function outer( arg ) {
				//代码执行时,局部变量被赋值
//				{
//					arg: 1,
//					local_var: 'foo',
//					inner: function() {
//						console.log('inner')
//					}
//				}					
				var local_var = 'foo'
				//执行环境上表示变量的属性保持不变,但当inner函数被调用时,在内部会创建一个新的执行环境
//				{
//					arg: 1,
//					local_var: undefined,
//					inner: function() {
//						console.log('inner')
//					}
//				}	
				function inner() {
					console.log('inner')
				}
				inner()
			}
			
/*************************************************************************/
			//script标签都在全局变量里面
			var globle_var
			//在全局执行环境中创建一个first_function()的执行环境
			first_function()
			function first_function() {
				var first_var = 'foo'
				//调用second_function()函数
				second_function()
			}
			//在全局执行环境中创建一个second_function()的执行环境
			function second_function() {
				//console.log(first_var)
				var second_var 
			}
			second_function()
			
			//注意:JavaScript中函数的作用域是通过词法来划分的,即定义函数时作用域链就固定了。
			//second_function函数不在first_function内,因此它无法访问first_function内的局部变量,尽管它是			//在first_function函数内被调用的
		</script>
	</head>
	<body>
	</body>
</html>
           

继续阅读