[TOC] #### 1. 立即执行函数介绍 --- JS 的立即执行函数: 函数在创建后立即执行 立即执行函数的作用只有一个: 创建一个独立的作用域,这个作用域里面的变量,外面访问不到,即:避免了变量污染 ```javascript const user = 'maria'; (function () { const user = 'hello' const age = 18 }()); console.log(user); // maria console.log(age); // Uncaught ReferenceError: age is not defined ``` #### 2. 立即执行函数语法 --- 使用 function 关键字 ```javascript // 第一种写法 (function () { // 函数体 })(); // 第二种写法 (function () { // 函数体 }()); ``` 箭头函数的写法 ```javascript // 第一种写法的箭头函数形式(正确语法) (() => { // 函数体 })(); // 第二种写法的箭头函数形式(错误语法) (() => { // 函数体 }()); ``` 接收立即执行函数的返回值 ```javascript const res = function (...params) { return params }('html', 'css', 'js'); const res = ((...params) => { return params })('html', 'css', 'js'); ```