js词法分析

当函数调用的前一瞬间,分析以下3个方面的东西,

1:参数2:局部变量声明3:函数声明

在函数运行的前一瞬间,先形成一个激活对象,叫Avtive Object, AO,AO的作用是用来存储一个函数相关的参数,局部变量等.函数内部无论是引用参数,还是引用局部变量,都到AO上找.

<script type="text/javascript">
function t3(x,y) {
    var x = 7;
    console.log(x); // 7
    console.log(y); // undefined
}
//t3(5);
/***
// 分析参数
AO[x,y]
// 分析变量声明
AO.x 已存在,不做任何影响.
AO[x,y]
// 执行过程
AO.x = 7
console.log(AO.x) ==> 7
console.log(AO.y) ==> undefined
***/

//------------------------------------

var str1 = 'global';
function t4() {
    console.log(str1); //global
    console.log(str2); //undefined

    var str2 = 'local';

    console.log(str2);//local
}

//t4();

/* 词法分析过程

分析参数
AO[]

分析局部变量
AO[str2] ,值是undefined

执行
console.log(str1);  // AO上找不到,到全局找
console.log(str2);  // AO上找到,值是undefined
*/

//------------------------------------

function t(x,y) {

    function x() {
        alert('hello');
    }

    var y = 99;

    console.log(x);  //function
    console.log(y);  //99
   
}

t(3,4);

/***
// 词法分析
// 分析参数
AO[x,y],

// 分析变量声明
AO[y],已存在,不做任何影响.

// 分析函数声明表达式
形成AO.x = funciton x() {alert('hello')}
***/

</script>

<script type="text/javascript">
/*
function t(x) {

    alert(x); // function
    
    function x() {
        alert(x);
    }

    alert(x); // function

}
t(1);

*/

function t(x) {

    alert(x); // 1
    
    var x = function () {
        alert(x);
    }

    alert(x); // function

}
t(1);



// 通过上面的例子可看出
// 函数声明表达式,和函数变量表达式的区别.

// function t () {} ,这种称为声明表达式, 立即影响AO
// var x = function () {} ,这种是等号右边是一个表达式,返回[函数类型的]值,把值赋给x,



</script>

<script type="text/javascript">
/*
function t(x) {

    alert(x); // function
    
    function x() {
        alert(x);
    }

    alert(x); // function

}
t(1);
*/
 
function t1(x) {

    alert(x); // function
    
    function x() {
        var x = 9;
        alert(x);
    }

    x(); // 9  如果var x = 9 屏蔽 ,结果是function

}
t1(1);

/**
// 分析参数
AO1
AO1[x]
AO1[x=1]

// 分析函数声明表达式
AO1[x=function(){}]

执行x函数:
AO2
AO2[]

// 执行内部alert(x)
**/


</script>

原文地址:https://www.cnblogs.com/lucky323ping/p/3520653.html