近期学习js中变量提升的一点东西

1变量提升:

就是说,以var声明的变量,它的声明会被提升到当前作用域的顶端(注意是变量声明提升,变量的赋值没有提升)

举一个例子:

 <script>
    console.log(a);//undefined
    var a = 10;
    function test(){
      console.log(a);//undefined
      var a =12;
      console.log(a);//12
    }
    test();
    console.log(a);//10
  </script>

上面代码相当于:

<script>
    var a;
    console.log(a);//undefined
    a = 10;
    function test(){
      var a;
      console.log(a);//undefined
      a =12;
      console.log(a);//12
    }
    test();
    console.log(a);//10
  </script>

2 那么如果用let和const声明的变量是否会提升?let和const是块级作用域

用以下例子进行测试:

 <script>
    console.log(a);//undefined
    var a = 10;
    function test(){
      console.log(a);//报错
      let a = 12;//or const a = 12;
      console.log(a);//12
    }
    test();
    console.log(a);//10
  </script>
View Code

得出结论:let和const,不适用于变量提升;let和const有着'临时性死区'的概念,即从作用域开始到变量申明的这一部分,不能使用该变量,否则会报错。

3函数的声明提升:

 函数声明方式有三种:

1函数声明:

function test(){};

2函数表达式:

var test = function(){};

3用Function构造函数://在es6中用class代替//后续补充

var test = new Function();

其中 函数声明及构造函数将会被提升:

用以下例子来证明:

<script>
   test();//输出:函数声明
    var test = function(){
      console.log("函数表达式");
    }
    test();//输出:函数表达式
    function test(){
      console.log("函数声明");
    }
    test();//输出:函数表达式
    var test = new Test();
    test.say();//输出:构造函数
    function Test(){
      this.say = function (){
        console.log("构造函数");
      }
    }
</script>

4函数声明高于变量声明:

如下:

<script>
    console.log(test);//输出:ƒ test(){
    //   console.log("函数申明");
    // }
    function test(){
      console.log("函数申明");
    }
    var test = 1;
</script>

注:个人记录,如果有错误的地方,欢迎大家指出。

猜你喜欢

转载自www.cnblogs.com/Zxq-zn/p/11441435.html