Javascript - 立即调用函数表达式

IIFE(立即调用函数表达式)

IIFE 是定义后立即运行的函数。

1
2
3
(function () {
console.log("runs immediately");
})();

箭头版本

1
2
3
(() => {
console.log("arrow IIFE");
})();

为什么用在后端?

  • 隔离变量
  • 运行启动配置一次
  • 避免全球污染
1
2
3
4
5
6
7
const config = (() => {
const PORT = 3000;
const ENV = "dev";
return { PORT, ENV };
})();

console.log(config.PORT);

下一主题: 异步/等待