解析变量的作用域

首先看代码

			function test(a) {

				console.log(a);

				var a = 5;

				function a() {}

				console.log(b);

				var b = 10;

				console.log(b);

				function b() {}

				console.log(a)

				var b = function() {};

				console.log(b);

			}

			test(1)

首先把5次输出结果分别打印出来方便大家看:

  1. function a() 函数a的函数体
  2. function b() 函数b的函数体
  3. 10 数字 10
  4. 5 数字 5
  5. function b(); 函数b的函数体

代码在执行之前系统会预编译 (预处理)操作;
1.创建GO对象
2.查找变量声明(带有var关键字) 并且将其赋值为undefined
GO{
a:undefined;
b:undefined;
}
3.查找函数声明( function 名字(){ } )把名字提出来,并且把函数体赋值给改名字
GO{
a:function a(){};
b:function b(){};
}
//执行代码
第一次输出 console.log( a );
预编译之后 第二步全局变量a赋值为undefined,第三步函数 a 赋值为 function a(){}
变量名字一样的情况下,后面的值会覆盖前面的值。 所以是function a() {}
第二次输出 console.log(b)
如同第一次步骤一样;后面的值覆盖前面的值 结果是function b(){};
第三次输出 console.log(b)
var b=10;全局变量b 赋值为10; 覆盖了编译时侯的值 结果是 10
第四次输出 console.log( a )
var a=5; 覆盖了变异时候a的值 结果是5
第五次 输出 console.log(b);
var b = function() {} 覆盖了之前var b=10;b的值; 结果是 function b(){};
这是在变量名和函数名字相同的情况下出现的。如果不一样就没有这些步骤。

猜你喜欢

转载自blog.csdn.net/qq_38743783/article/details/84632731