预解析

//解析规则
//在代码执行时,让函数声明和变量声明提升
// 1.变量,函数同名,函数优先级高,覆盖变量
// 2.变量提升,不赋值
// 3.函数提升,不调用
// 4.同名变量,第一个生效
// 5.同名函数,后面覆盖前面
   1. // 以下代码执行输出结果是什么
    (function d(num) {
      console.log(num);
      var num = 10
    }(100));//100

    (function e(num) { //同名函数覆盖变量
      console.log(num);
      var num = 10;
      function num() { };
    }(100));//num函数 

    (function f(num) {
      function num() { };
      console.log(num);//num函数 
      var num = 10
      console.log(num);//10
    }(100));
  2. function m() {
      console.log(a1); //undefined
      console.log(a2); //undefined
      console.log(b1); //undefined
      console.log(b2); //undefined
      if (false) {
        function b1() { };
        var a1 = 10;
      }
      if (true) {
        function b2() { };
        var a2 = 10;
      }
      console.log(a1); //undefined
      console.log(a2); //10
      console.log(b1); //undefined
      console.log(b2); //b2函数
    }
    m();
3.
   console.log(a);//a函数
    var a = 1;
    function a() {
      console.log(2);
    }
    console.log(a);//1
    a();//报错
//变量的搜索规则
//1.先看自己作用域里面有没有这个变量,如果没有,往外一层一层就近查找
//2.如果一致找到全局,没有找到,那就会报错
    //预解析
    //var a = 9, a是局部变量
    //b = 9 , c = 9  b,c是隐式全局变量
   fn3();
    console.log(c);//9
    console.log(b);//9
    console.log(a);//报错

    function fn3() {
      var a = b = c = 9;
      console.log(a);//9
      console.log(b);//9
      console.log(c);//9
    }
2.
    var color = "red";
    function outer() {
      var anotherColor = "blue";

      function inner() {
        var tmpColor = color;//tmpColor = 'red'
        color = anotherColor;//color = 'blue'
        anotherColor = tmpColor;//anotherColor = 'red'
        console.log(anotherColor);//'red'
      }

      inner();
    }
    outer();
    console.log(color);//blue
原文地址:https://www.cnblogs.com/z-lin/p/10961387.html