近期学习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>

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

转载于:https://www.cnblogs.com/Zxq-zn/p/11441435.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值