惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

PCI Perspectives
PCI Perspectives
P
Proofpoint News Feed
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
T
Tenable Blog
I
Intezer
Scott Helme
Scott Helme
Hacker News - Newest:
Hacker News - Newest: "LLM"
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Security Latest
Security Latest
SecWiki News
SecWiki News
Schneier on Security
Schneier on Security
T
The Exploit Database - CXSecurity.com
The Last Watchdog
The Last Watchdog
N
News and Events Feed by Topic
Google DeepMind News
Google DeepMind News
S
Secure Thoughts
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
H
Hacker News: Front Page
L
LINUX DO - 最新话题
U
Unit 42
宝玉的分享
宝玉的分享
Stack Overflow Blog
Stack Overflow Blog
L
LINUX DO - 热门话题
IT之家
IT之家
C
Cybersecurity and Infrastructure Security Agency CISA
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
量子位
博客园_首页
爱范儿
爱范儿
T
Threatpost
小众软件
小众软件
A
Arctic Wolf
Jina AI
Jina AI
H
Help Net Security
Webroot Blog
Webroot Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyberwarzone
Cyberwarzone
博客园 - 聂微东
月光博客
月光博客
The Register - Security
The Register - Security
Martin Fowler
Martin Fowler
博客园 - 司徒正美
V
V2EX
博客园 - Franky
B
Blog
B
Blog RSS Feed
H
Heimdal Security Blog
WordPress大学
WordPress大学
A
About on SuperTechFans

开飞机的老张

AGENTS.md Openspec 使用心得 从树莓派内网穿透到 Cloudflare Pages Openclaw和博客 郊眠寺 采石 译:我为什么使用Map(和WeakMap)处理DOM节点 介绍JavaScript中Symbol 原生JavaScript获取URL参数 字符串首字母大写 用forEach()遍历对象 JavaScript禁用按钮 JavaScript的FormData JavaScript的Blob 用FileReader读取本地文件 JavaScript的Thenable JavaScript中Promise的reject JavaScript的Promise链 用interact.js实现拖拽、缩放、吸附
JavaScript的立即调用函数表达式(IIFE)
kaifeiji.cc · 2023-07-25 · via 开飞机的老张

原文:Immediately Invoked Function Expressions (IIFE) in JavaScript

JavaScript的立即调用函数表达式(IIFE)是一种常用于变量闭包的设计模式。

立即调用函数表达式(简称IIFE)是一种JavaScript的设计模式,它声明了一个匿名函数并立即执行。

1
2
3
4

(function() {
console.log('Hello, World!');
})();

在IIFE模式中也可以用箭头函数:

1
2
3
4

(() => {
console.log('Hello, World!');
})();

function() { ... }外边的小括号是必要的:如果没有小括号,将会报语法错误。因为小括号告诉JavaScript语言解析器,将函数定义当作表达式进行处理。

为何使用IIFEs?

IIFE非常有用,它可以定义IIFE之外无法访问的局部变量。例如,IIFE可以在浏览器顶层上下文中执行JavaScript,却不会污染全局作用域。

1
2
3
4
5
6
7
8
<script>

(function() {
var answer = 42;
})();

typeof answer;
</script>

有时也会看到IIFE用于包裹一些计算需要用的临时变量,而这些临时变量又不想暴露给其他计算过程。例如,要计算购物车的总价,但又不想把salesTax变量泄露给外部作用域:

1
2
3
4
5
const subtotal = 40;
const total = (function() {
const salesTax = product.salesTaxRate * subtotal;
return subtotal + salesTax;
})();

一元运算符

如果对IIFE使用一元运算符(例如void运算符),可以省略IIFE外的小括号。

1
2

void function() { console.log('Hello, World'); }();

在生产环境很少见到这种模式用void。但这种模式在async函数非常有用,因为await就是一个一元运算符。可以await一个async的IIFE:

1
2
3
4
const answer = await async function() {
return 42;
}();
answer;

本教程对您有帮助吗?来GitHub仓库点个星支持我们吧!