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

推荐订阅源

MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Spread Privacy
Spread Privacy
AI
AI
宝玉的分享
宝玉的分享
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
Cyber Attacks, Cyber Crime and Cyber Security
爱范儿
爱范儿
Help Net Security
Help Net Security
V
Visual Studio Blog
大猫的无限游戏
大猫的无限游戏
Forbes - Security
Forbes - Security
P
Privacy & Cybersecurity Law Blog
Project Zero
Project Zero
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队
T
Troy Hunt's Blog
美团技术团队
T
Threatpost
K
Kaspersky official blog
V
V2EX
Scott Helme
Scott Helme
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
V
Vulnerabilities – Threatpost
Last Week in AI
Last Week in AI
PCI Perspectives
PCI Perspectives
Google Online Security Blog
Google Online Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
Engineering at Meta
Engineering at Meta
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
I
InfoQ
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
L
LINUX DO - 最新话题
T
The Exploit Database - CXSecurity.com
L
LangChain Blog
S
Security @ Cisco Blogs
The Last Watchdog
The Last Watchdog
H
Hacker News: Front Page
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
TaoSecurity Blog
TaoSecurity Blog

开飞机的老张

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仓库点个星支持我们吧!