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!”

相关文章:

  • 2022-12-23
  • 2022-01-22
  • 2021-12-07
  • 2022-12-23
  • 2022-02-20
  • 2021-07-20
  • 2022-12-23
  • 2021-06-16
猜你喜欢
  • 2021-09-04
  • 2022-03-04
  • 2021-10-13
  • 2021-11-07
  • 2021-10-13
  • 2021-12-20
  • 2021-07-21
相关资源
相似解决方案