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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
T
Troy Hunt's Blog
Help Net Security
Help Net Security
L
LINUX DO - 最新话题
aimingoo的专栏
aimingoo的专栏
Microsoft Azure Blog
Microsoft Azure Blog
Y
Y Combinator Blog
Attack and Defense Labs
Attack and Defense Labs
M
MIT News - Artificial intelligence
Security Archives - TechRepublic
Security Archives - TechRepublic
SecWiki News
SecWiki News
博客园 - 三生石上(FineUI控件)
P
Privacy International News Feed
AI
AI
PCI Perspectives
PCI Perspectives
L
Lohrmann on Cybersecurity
G
Google Developers Blog
N
News | PayPal Newsroom
Hugging Face - Blog
Hugging Face - Blog
B
Blog RSS Feed
The Hacker News
The Hacker News
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
I
InfoQ
Webroot Blog
Webroot Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
U
Unit 42
A
About on SuperTechFans
Cyberwarzone
Cyberwarzone
Schneier on Security
Schneier on Security
Cisco Talos Blog
Cisco Talos Blog
D
Docker
博客园_首页
The Cloudflare Blog
S
Secure Thoughts
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Last Watchdog
The Last Watchdog
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
I
Intezer
Google DeepMind News
Google DeepMind News
Know Your Adversary
Know Your Adversary
Simon Willison's Weblog
Simon Willison's Weblog

开飞机的老张

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