[ES6] 05. The leg keyword -- 3. Block Scope

In ES6, IIFE is not necessary:

// IIFE写法
(function () {
    var tmp = ...;
    ...
}());

// 块级作用域写法
{
    let tmp = ...;
    ...
}

 

另外,ES6也规定,函数本身的作用域,在其所在的块级作用域之内

function f() { console.log('I am outside!'); }
(function () {
  if(false) {
    // 重复声明一次函数f
    function f() { console.log('I am inside!'); }
  }

  f();
}());

上面代码在ES5中运行,会得到“I am inside!”,但是在ES6中运行,会得到“I am outside!”

 

(function () {
    if(true) {
        // 重复声明一次函数f
        function f() { console.log('I am inside!'); }
        f();
    }


}());
function f() { console.log('I am outside!'); }

上面代码在ES6中运行,会得到“I am inside!”

posted @ 2014-11-19 23:44  Zhentiw  阅读(318)  评论(0编辑  收藏  举报