javascript高级课程-2

作用域  var作用 词法分析

js作用域

    var a=12;
    function a1(){
        var a=11;
        function b(){
            function c(){
                console.log(a);
            }
            c();
        }
        b();
    }
    a1();
    /*变量是如何寻找的
    首先在函数内寻找
    寻找不到 则到外层函数寻找
    指导全局区域
    */

var的用处

var a=12;
    b=1;
    function test(){
        var c=12;//局部变量
        b=2;//不加var 向外找找到全局变量b并且赋值
    }
    test();
    console.log(b);//打印全局变量

词法分析:

1、先分析参数

2、再分析变量声明

3、分析函数声明

具体步骤:

1、函数运行前的一瞬间、生成活动对象 简称AO

2、函数声明的参数,形成AO属性,值为实参的值,未传实参则为undefined

3、分析变量声明:如var age 

    如果AO上还没有age属性,则添加AO属性值为undefined

    如果AO上已经有age属性则不作任何影响

4、分析函数声明,如function foo(){};

     则把含赋值给AO.foo属性

     如果属性已经存在则无情覆盖

var a=12;
    b=1;
    function test(c){
        /*词法分析过程:
        形参分析:
        test.AO.c=12;
        声明变量分析
        test.AO.c=undefined
        如果前面形参分析已经存在该属性 则不影响
        否则赋值
        函数声明略过
        */
        var c=1;//局部变量
        console.log(c);//执行时c被赋值为12
    }
    test();


    function test2(g){
        console.log(g);
        function g(){
            alert(2);
        }
    }
    test2(12);
    /*注意函数声明分析部分 虽然这里不像test一样执行时覆盖掉AO上的实参g属性,但这个是再词法分析过程时强行覆盖掉*/

    function test3(g){
        console.log(g);
        var g = function(){//此时词法分析过程将g看成一个声明的变量而不是函数
            alert(2);
        }
    }
    test3(12);

再看一个例子:

t();
    t2();
    function t(){
        alert('t');
    }
    var t2=function(){//词法分析分析过程t2为声明 表达式值为undefended 无法执行
        alert('t2');
    }

 复杂例子:

    function test(a){
        alert(a);
        function a(){
            alert(a);
        }
        a();
    }
    test(12);

    /*
    分析外层test
    test.AO={}
    分析参数
    test.AO.a=12
    分析声明变量
    分析声明函数
    test.AO.a=function(){
            alert(a);
        }
    执行test(12)
    输出函数
    分析函数a
    分析参数
    分析声明变量
    分析声明函数
    执行a()
    找不到a 到外层test.AO中找
    输出函数



    */
function test1(a){
        alert(a1);
        var a1 = function(){
            alert(a1);
        }
        a1();
    }
    test1(12);
    /*
    词法分析
    test1
    test1.AO={}
    test1.AO.a=12
    test1.AO.a1=undefined
    执行test1
    弹出undefined
    并且a1赋值为函数function(){
            alert(a1);
        }
    词法分析test1()
    执行test2
    a1到外层找
    弹出函数

    */
原文地址:https://www.cnblogs.com/webcyh/p/11387941.html