JS 预编译

0. 预编译的理解

JavaScript 是解释性语言, 即编译一行, 执行一行. 但在编译前存在预编译过程.

预编译分为两种, 全局的预编译(代码执行前)和函数的预编译(函数执行前).

1. 函数预编译

1.生成 Activation Object 对象

2.寻找形参和变量声明, 将其作为 AO 属性名, 值为 undefined

3.形参值为实参

4.寻找函数声明, 函数名作为 AO 属性名, 值为函数体

例如

 <script>
  function game(a) {
    console.log(a);
    var a = 123;
    console.log(a);
    function a(){};
    console.log(a);
    var b = function(){};
    console.log(b);
  }
  game(0);
 </script>

结果为

ƒ a(){}
123
123
ƒ (){}

过程如下

1.生成 AO, 寻找形参和变量声明, 值为 undefined

AO :{
    a: undefined,
    b: undefined
}

2.形参值为实参

AO :{
    a: 0,
    b: undefined
}

3.函数声明, 值为函数体

AO :{
    a: function a() {},
    b: undefined,
}

2. 全局预编译

1.生成 Globa Object

2.找变量声明, 如果 window 存在当前属性, 会忽略, 否则变量会作为属性名, 值为 undefined

3.找函数声明, 同 2, 如果 window 没有, 属性为函数名, 值为函数体

例如

 <script>
  console.log(a);
  var a = 1;
  console.log(a);
  function game(a){
    console.log(a);
    var a = 123;
    console.log(a);
    function a() {};
    console.log(a);
    console.log(b);
    var b = function(){};
    console.log(b);
  }
  game(0);
 </script>

结果

undefined
0
ƒ a() {}
123
123
undefined
ƒ (){}

3. 常见考题

例题一

    <script>
      function test() {
        console.log(b);
        if (a) {
          var b = 100;
        }
        console.log(b);
        c = 234;
        console.log(c);
      }
      var a;
      test();
      a = 10;
      console.log(c);
    </script>

解答

undefined
undefined
234
234

例题二

例题三

例题四

例题五

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值