JavaScript 预编译

文章目录

  • 预编译四步
  • 实例分析
    • 注意


预编译四步

函数中的预编译:

  1. 创建AO活动对象(Active Object)
  2. 找形参和变量声明,将变量和形参名作为AO属性名,赋值为undefined
  3. 实参值赋给形参(函数)
  4. 找到函数声明,值赋予函数体

全局类似,创建的对象为GO全局对象(Global Object),即window对象

实例分析

    function f(a){
        console.log(a);

        var a = 123;

        console.log(a);
        
        function a() {}

        console.log(a);

        console.log(b);

        var b = function () {};

        console.log(b);
    }

    f(1);

过程分析

1.创建 AO 对象
2.先找变量声明
	a --> undefined
	b --> undefined
3.实参值赋给形参
	a --> 1
	(b --> undefined)
4.找到函数声明,赋予函数体
	a --> function a() 
	(b --> undefined)    **注意是函数声明,b是函数表达式**

输出结果

顺序执行
	 function a()
	 // 赋值 123
	 123
	 123
	 undefined
	 function b()

注意

  1. 四步中函数声明提升在变量提升之后,会赋值函数体覆盖undefined
  2. 函数声明和函数表达式不同,函数表达式类即变量声明赋值undefined
  3. if 中的函数声明不会参与预编译
	console.log(a);

	if(1){
	  function a(){}
	}

	console.log(a);   输出function a()

只有在执行 if 中语句后才会赋值

你可能感兴趣的:(Javascript)