zoukankan      html  css  js  c++  java
  • ES6(块级作用域)

           我们都知道在javascript里是没有块级作用域的,而ES6添加了块级作用域,块级作用域能带来什么好处呢?为什么会添加这个功能呢?那就得了解ES5没有块级作用域时出现了哪些问题。

           ES5在没有块级作用域的情况下出现的问题:

           一。在if或者for循环中声明的变量会泄露成全局变量

    for(var i=0;i<=5;i++){
          console.log("hello");
    }
    console.log(i); //5

          二。内层变量可能会覆盖外层变量

    var temp = new Date();
    function  f(){
         console.log(temp);
         if(false){
             var temp = "hello";
        }
    }
    f(); //undefined

         不管最后是否执行if语句,都会输出undefined,因为temp会提升到函数顶部,因此覆盖了外部的变量temp。

         上一篇介绍的let和const命令,它们所声明的变量只在所在的代码块内有效,即为js添加了块级作用域。

               【1】允许块级作用域任意嵌套;

    {{{let tmp = "hello world"}}}

               【2】外层作用域无法读取内层作用域的变量;

    {{{
       {let tmp = "hello world";}
       console.log(tmp);  //error
    }}}

               【3】内层作用域可以定义外层作用域的同名变量

    {{{
       let tmp = "hello world";
       {let tmp = "hello world";}
    }}}

               【4】函数本身的作用域在其所在的块级作用域之内。

    function f(){
        console.log("outside");
    }
    (function(){
        if(false){
            function f(){
                console.log("inside");
            }
        }
       f();
    }());

    这段代码如果是在ES5中运行,那么会输出inside,因为在ES5中,函数会提升到作用域的顶部,如果是在ES6中运行,则会输出outside,因为在ES6中函数无法提升,所以访问到的f()是外层的f()。

             【5】在ES5中,因为没有块级作用域,获得广泛运用的是立即执行函数。现在ES6增加了块级作用域,那么立即执行函数就不再必要了

    //立即执行函数
    (function(){
        var temp = "hello world";
    }());
    //块级作用域
    {
       var temp = "hello world";
    }

           【6】在严格模式下,函数只能在顶级作用域和函数内声明,在if代码块和循环代码块下的声明都会报错。

  • 相关阅读:
    【jquery ,ajax,php】加载更多实例
    关于scrollTop
    jquery 底部导航透明度变化
    jquery 处理密码输入框(input type="password" ) 模仿placeholder
    物化视图基于rowID快速刷新
    ora-01653 无法通过1024扩展
    oracle临时表空间
    java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer
    redis 简单使用
    BigDecimal 运算
  • 原文地址:https://www.cnblogs.com/yezi-dream/p/6168557.html
Copyright © 2011-2022 走看看