ES6作用域

2018-07-05  本文已影响0人  秋玄语道

涉及变量提升和闭包

   <script type="text/javascript">
      //ES5
       const callbacks = []
       for(var i = 0; i<3; i++){
           callbacks[i] =function () {
               return i*2
           }
       }
       console.table([
           callbacks[0](),
           callbacks[1](),
           callbacks[2]()
       ]);
   //ES6
       const callbacks = []
       for(let i = 0; i<3; i++){
           callbacks[i] =function () {
               return i*2
           }
       }
       console.table([
           callbacks[0](),
           callbacks[1](),
           callbacks[2]()
       ]);
 </script>
   <script type="text/javascript">
       //ES5
       ((function () {
          const  foo =function () {
              return 1
          }
          console.log("foo()===1",foo() ===2)
          ;((function () {
              var foo =function () {
                  return 2
              }
              console.log("foo()===2",foo() === 2)
          })())
       })())
       //ES6
       {
           function foo() {
               return 1
           }
           console.log('foo()===1',foo() === 1);
           {
               function foo() {
                   return 2
               }
               console.log('foo()===2',foo() === 2)
           }
       }
   </script>
上一篇 下一篇

猜你喜欢

热点阅读