- 全局变量
- 直接定义全局变量,未初始化的变量保存值为undefined
- 在函数体中不适用var操作符可以定义全局变量(很难维护,不要这么干)
var message;
console.log(message); // undefined
var message = "hi";
console.log(message); // "hi"
message = 100; // 有效 但是不推荐
- 局部变量
- 只在当前作用域可以访问(函数,循环体)
- 超出作用域会销毁
- 子作用域可以访问父级作用域的变量,父级不能访问子级
function test() { var message = "hi"; //局部变量 messageTest = 100; //全局变量 } test(); alert(message); // ReferenceError: message is not defined alert(messageTest); // 100
- 预编译(作用域创建的阶段即预编译阶段)
- JS变量对象 函数作用域称作AO对象Activation Object
function fn(a,c) { console.log(a) //ƒ a() { } var a = 123 console.log(a) //123 console.log(c) //ƒ c() { } function a() { } if (false) { var d = 678 } console.log(d) //undefined console.log(b) //undefined var b = function() { } console.log(b) //ƒ () { } function c() { } console.log(c) //ƒ c() { } } fn(1,2)
- AO对象加载顺序
- 创建一个AO对象
AO{}
AO:{}
- 将函数内的所有参数和变量声明(的名)储存到AO对象中,
value
为undefined
AO:{ a: undefined, c: undefined, d: undefined, b: undefined, }
- 将形参和实参进行统一
AO:{ a: 1, c: 2, d: undefined, b: undefined, }
- 找函数声明的函数名作为AO对象中的key,覆盖原有的变量声明,函数整体内容为value储存到AO对象中
AO:{ a: function a() { }, c: function c() { }, d: undefined, b: undefined, }
- 综合案例
function fun() {
var a=b=c=1;
}
fun();
console.log(a); // ReferenceError: a is not defined
console.log(b); // 1
console.log(c); // 1
参考:
https://blog.51cto.com/11871779/2120006
https://www.jianshu.com/p/cf648fe2c525