JS预编译

JS预编译

    • 函数的预编译
      • 函数执行步骤
    • 加上全局变量的预编译

  1. 通篇检查语法错误
  2. 预编译
  3. 开始解释一行,执行一行

函数的预编译

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

打印结果
JS预编译_第1张图片

函数执行步骤

在函数执行前的一瞬间会生成自己的AO,(Activation Object,活跃对象也叫函数上下文,如果函数执行2次,生成了两次AO,这两次的AO是没有任何关联),变量都会挂载到AO中,具体步骤如下

  1. 寻找形参和变量声明
  2. 实参值赋值给形参
  3. 寻找函数声明并赋值函数体
  4. 从函数体第一行开始逐行执行

结合本例讲解

  1. 寻找形参和变量声明
AO={
  a:undefined,// 形参
  b:undefined,// 变量声明
}
  1. 实参值赋值给形参
AO={
  a:undefined -> 2,// 实参值2赋值给形参a
  b:undefined,
}
  1. 寻找函数声明并赋值函数体
AO={
  a:undefined -> 2 -> function a() {},// 寻找函数声明并赋值函数体
  b:undefined,
  d:function d() {} //寻找函数声明并赋值函数体
}
  1. 从函数体第一行开始逐行执行
 function test(a) {
   console.log(a); // function a() {}
   var a = 1; // 将1赋值给a,a:undefined -> 2 -> function a() {} -> 1
   console.log(a); // 1
   function a() {} // 第3步已预编译,执行时此行无影响
   console.log(a) // 1
   var b = function(){} // 将function(){}赋值给b,即b:undefined -> function(){}
   console.log(b); // function(){}
   function d() {} // 第3步已预编译,执行时此行无影响
 }

从预编译到执行结束,值的全部变化过程:

AO={
  a:undefined -> 2 -> function a() {} -> 1,
  b:undefined -> function(){},
  d:function d() {} 
}

加上全局变量的预编译

  var b = 3;
  console.log(a);

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

预编译时,全局变量挂载到GO(Global Object,即全局对象)上

  1. 寻找变量
  2. 寻找函数声明
  3. 执行

结合本例讲解

1. 寻找变量

  GO = {
    b:undefined
  };

2. 寻找函数声明

  GO = {
    b:undefineda: function a(a) {
	    console.log(a);
	    var a = 2;
	    console.log(a);
	    function a() {}
	    var b = 5;
	    console.log(b)
	  }
  };

3. 执行
当执行到a(1);时,开始生成AO

  GO = {
    b:undefined,->3
    a: function a(a) {
	    console.log(a);
	    var a = 2;
	    console.log(a);
	    function a() {}
	    var b = 5;
	    console.log(b)
	  }
  };
  AO = {
    a:undefined,->1->function a() {},
    b:undefined
  }

结束预编译

你可能感兴趣的:(JavaScript,javascript,前端,vue.js)