AO 和 GO
AO activation object 活跃对象 函数上下文
1 寻找形参和变量声明
2 实参值赋值给形参
3 找函数声明,赋值
4 执行
GO global object 全局上下文
1 找变量
2 找函数声明
3 执行
AO GO 作用域
作用域链相关所产生的一切问题
AO -> function 独立的仓库
// 对象
function test(a, b){}
函数也是一种对象类型 引用类型 引用值
test.name test.length test.prototype
对象 -> 有些属性是我们无法访问的
JS 引擎内部固有的隐式属性
作用域和作用域链
[[scope]]
- 函数创建时,生成的一个JS内部的隐式属性。
函数存储作用域链的容器,作用域链
- AO /GO
- AO, 函数的执行期上下文
- GO,全局的执行器上下文
- 函数执行完成以后,AO 是要销毁的
- AO 是一个即时的存储容器
a函数被定义
每个函数定义时,就已经包含了GO
- a函数执行前 预编译

- a函数执行时,b函数被定义(在上级环境之中,即a函数)作用域链与a函数作用域链一样

- b函数执行前

- b函数执行之后

- a函数执行之后

- 最后

全局执行的前一刻 GO-> 函数声明已经定义
全局执行
GO = {test: undefined -> function(){}test2: function test2(){...}}test2();function test2() {}test();var test = function(){}
上级在执行时,下级被定义
// 函数被定义时,已经形成作用域[[scope]] -> scope chain -> GO -> AO(函数被执行)// 函数执行时,才会形成自己的AOfunction test2(){function test3(){}}
执行才会生成对应的AO
function a(){function b(){function c(){}c();}b();}a();a定义: a.[[scope]] -> 0: GOa执行: a.[[scope]] -> 0: a -> AO 1: GOb定义: b.[[scope]] -> 0: a -> AO 1: GOb执行: b.[[scope]] -> 0: b -> AO 1: a -> AO 2: GOc定义: c.[[scope]] -> 0: b -> AO 1: a -> AO 2: GOc执行: c.[[scope]] -> 0: c -> AO 1: b -> AO 2: a -> AO 3: GOc结束: c.[[scope]] -> 0: b -> AO 1: a -> AO 2: GOb结束: b.[[scope]] -> 0: a -> AO 1: GOc.[[scope]] 删除了a结束: a.[[scope]] -> 0: GOb.[[scope]] 删除了
闭包
闭包就是能够读取其他函数内部变量的函数。 由于在Javascript语言中,只有函数内部的子函数才能读取局部变量,因此可以把闭包简单理解成”定义在一个函数内部的函数”。 在本质上,闭包就是将函数内部和函数外部连接起来的一座桥梁。
function test1(){function test2(){var b = 2;console.log(a);}var a = 1;return test2();}var c = 3;var test3 = test1();test3();
- test1被定义

- test1执行前一刻, tes2被定义, 此时两个函数作用域链一样

- return test2; test2还没有执行,只是被return出去了 test1结束

- return test2赋值给test3 test3执行,即test2被执行 test3存放的是test2的引用

- 执行结束,只销毁test2的AO

当内部函数被返回到外部并保存时,一定会产生闭包,闭包会产生原来的作用域链不释放,过度的闭包可能会导致内存泄漏或者加载过慢。 ```javascript function test(){ var n = 100;
function add(){
n++;
console.log(n); }
function reduce(){
n--;
console.log(n); }
return [add, reduce]; }
var arr = test(); arr0; // 101 arr1; // 100
// 闭包也是一种数据缓存```javascriptfunction sunSched(thing){var sunSched = '';var operation = {setSched: function(){sunSched = thing;},showSched: function() {console.log("My schedule on sunday is " + thing);}}return operation;}var sunSched = sunSched();sunSched.setSched('studying');sunSched.showSched(); // My schedule on sunday is studying
