函数上下文(AO)

当进入执行上下文时,这时候还没有执行代码,

变量对象会包括:

函数的所有形参和声明变量 (如果是函数上下文)

1.由形参和声明变量的名称为属性被创建;

2.没有实参,属性值设为 undefined

实参赋值给形参

1.找到形参名称的属性,将其属性值由undefined改为实参值

函数声明

1.由名称和对应值(函数对象(function-object))组成一个变量对象的属性被创建

2.如果变量对象已经存在相同名称的属性,则完全替换这个属性

最后在执行函数

例子:

function test(a){
    console.log(a);
    var a=1;
    console.log(a);
    function a(){}
    console.log(a);
    console.log(b);
    var b=function(){}
    console.log(b);
    function c(){}
}
test(2)

1.AO = {
    a: undefined,
    b: undefined,
}
2.AO = {
    a: undefined->
    2,
    b: undefined,
}
3.AO = {
    a: undefined ->
        2 ->
        function a(){},
    b: undefined,
    c: function c(){},
}
4.AO = {
    a: undefined ->
        2 ->
        function a(){}->
        1,
    b: undefined -> function b(){},
    c: function c(){},
}
function test(){
    return a;
    a=1;
    function a(){}
    var a=2;
}
console.log(test()); // function a(){}

AO={
    a:undefined -> function a(){}
}
console.log(test()); //2
function test() {
    a = 1;
    function a() { }
    var a = 2;
    return a;
}
AO = {
    a: undefined -> function a() { }->1->2
}
a=1;
function test(e){
    function e(){}
    arguments[0]=2;
    console.log(e); // 2
    if(a){
        var b=3;
    }
    var c;
    a=4;
    var a;
    console.log(b); // undefined
    f=5;
    console.log(c); // undefined
    console.log(a); // 4
}
var a;
test(1);
console.log(a); // 1
console.log(f); // 5

GO={
    a:undefined ->1,
    test:function test(){...},
    f:5
}
AO={
    e:undefined->1->function e(){}->2,
    b:undefined,
    c:undefined,
    a:undefined->4,
}
function foo() {
    console.log(a);
    a = 1;
}

foo(); // ???

function bar() {
    a = 1;
    console.log(a);
}
bar(); // ???

第一段会报错:Uncaught ReferenceError: a is not defined

第二段会打印:1

这是因为函数中的 "a" 并没有通过 var 关键字声明,所有不会被存放在 AO 中。

第一段执行 console 的时候, AO 的值是:

AO = {
    arguments: {
        length: 0
    }
}

没有 a 的值,然后就会到全局去找,全局也没有,所以会报错。

当第二段执行 console 的时候,全局对象已经被赋予了 a 属性,这时候就可以从全局找到 a 的值,所以会打印 1。

原文地址:https://www.cnblogs.com/ssszjh/p/12926638.html