作用域链
[[scope]] 中所存储的执行期上下文对象的集合.这个集合呈链式链接,我们把这种链式连接叫做作用域链
查找变量:
在哪个函数里面查找变量我们就从那个函数的作用域链的顶端依次向下查找
例:
function a ()
{
function (b)
{
var b = 234
}
var a = 123
b();
}
一个 函数执行完后,将会销毁执行上下文
a函数被创建 [[scope]] 0 ----> GO
b函数被创建 [[scope]] 0 ----->AO(a)
[[scope]] 1 ------>GO
b函数被执行 [[scope]] 0 ------>AO(b)
[[scope]] 1 ------>AO(a)
[[scope]] 2 ------>GO
闭包 但凡是内部函数被保存在外部,一般都是闭包,闭包的会导致原有的作用域链不释放,造成内存泄露
function a() {
var num = 100;
funcion b ()
{
` num ++;
console.log(num;
}
return b;
}
var demo = a();
demo();
demo();
闭包的作用
实现公有变量 :函数累加器
function add()
{
var count = 0;
function demo(){
count ++;
}
return demo;
}
var counter= add()
可以做缓存(存储结构)
function test() {
var num = 100;
function a(){
num ++;}
function b(){
num--;
}
return [a,b];
}
var myArr = test();
myArr[0]();
myArr[1]();
他们都会拿到test的AO而且是同一个,所以a改变的num的值,会影响到b函数中num的值
function eater() {
var food= "";
var obj = {
eat :function () {
console.log("i am eating " = food);
food = myFood;
}
push :function (myFood)
{
food = myFood;
}
return obj
}
}