前端面试必备(1)预编译

目录

我们先看这道题:

预编译

预编译的时候做了哪些事情?

那么这个AO对象在函数作用域的创建阶段做了哪些事情呢?

js的解释执行  逐行执行


gitee仓库地址获取代码:https://gitee.com/CMD-UROOT/case-interview

我们先看这道题:

建议自己先思考怎么解决,再看解题思路

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>预编译</title>
</head>
<body>
  <script>
    function fn(a,c) {
      console.log(a)
      var a = 123
      console.log(a)
      console.log(c)
      function a() {}
      if (false) {
        var d = 678
      }
      console.log(d)
      console.log(b)
      var b = function () {}
      console.log(b)
      function c () {}
      console.log(c)
    }
    fn(1,2)
  </script>
</body>
</html>

解决这道题我们需要了解预编译
 

预编译

作用域的创建阶段就是预编译的阶段

预编译的时候做了哪些事情?

作用域分为全局的作用域和函数的作用域

在函数的作用域创建阶段与之对应的有一个js的变量对象(也称为AO对象) ,我们是访问不到的,是供js引擎自己去访问的

那么这个AO对象在函数作用域的创建阶段做了哪些事情呢?

1.创建了ao对象

A0:{

}

2.找形参和变量的声明  作为ao对象的属性名 值是undefined

A0:{

a:undefined      

c:undefined      

d:undefined

b:undefined

}

3.实参和形参相统一

统一后:

A0:{

a:undefined      1

c:undefined      2

d:undefined

b:undefined

4.找函数声明 会覆盖变量的声明

覆盖后:也就是预编译阶段已经完成

A0:{

a:undefined      1  function a() {}

c:undefined      2  function c() {}

d:undefined

b:undefined

}

 js的解释执行  逐行执行

现在我们对照预编译阶段已经完成的AO对象来做题,就如有神助了!

A0:{

a:undefined      1  function a() {}

c:undefined      2  function c() {}

d:undefined

b:undefined

}

 

 完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>预编译</title>
</head>
<body>
  <script>
    function fn(a,c) {
      console.log(a) //function a() {}
      var a = 123
      console.log(a) //123
      console.log(c) //function c() {}
      function a() {}
      if (false) { //这里是false并不会进来
        var d = 678
      }
      console.log(d) //undefined
      console.log(b) //undefined
      var b = function () {} //这里b赋值为function(){},所以下面打印b就是function(){}
      console.log(b) //function () {}
      function c () {} //并不执行
      console.log(c)  //function c() {}
    }
    fn(1,2)
    

    // AO:{
    //   a:undefined 1 function a() {}
    //   c:undefined 2 function c() {}
    //   d:undefined
    //   b:undefined
    // }
  </script>
</body>
</html>

控制台打印验证:

猜你喜欢

转载自blog.csdn.net/qq_46368050/article/details/125100125
今日推荐