Web/04-JavaScript基础/22-立即执行函数.md
qianguyihao 4b3f7bade5 rename
2022-10-09 15:12:20 +08:00

58 lines
953 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 22-立即执行函数
---
<ArticleTopAd></ArticleTopAd>
## 立即执行函数 IIFE
### 概念
函数定义完,就立即被调用,这种函数叫做立即执行函数。英文是 IIFEImmediately-invoked function expression立即调用函数表达式。
### 语法格式
语法1
```js
(function() {
// 函数体
})();
```
语法2立即执行函数也可以传参
```js
(function() {
// 函数体
})(a, b);
```
语法解释:
- `function(){}`这种写法,需要再加一对圆括号,变成``
### 举例
现有匿名函数如下:
```javascript
function(a, b) {
console.log("a = " + a);
console.log("b = " + b);
};
```
立即执行函数如下:
```javascript
(function(a, b) {
console.log("a = " + a);
console.log("b = " + b);
})(123, 456);
```
立即执行函数往往只会执行一次。为什么呢?因为没有变量保存它,执行完了之后,就找不到它了。