1. 立即執(zhí)行函數(shù)介紹
JS 的立即執(zhí)行函數(shù): 函數(shù)在創(chuàng)建后立即執(zhí)行
立即執(zhí)行函數(shù)的作用只有一個(gè): 創(chuàng)建一個(gè)獨(dú)立的作用域,這個(gè)作用域里面的變量,外面訪問(wèn)不到,即:避免了變量污染
const user = 'maria';
(function () {
const user = 'hello'
const age = 18
}());
console.log(user); // maria
console.log(age); // Uncaught ReferenceError: age is not defined
2. 立即執(zhí)行函數(shù)語(yǔ)法
使用 function 關(guān)鍵字
// 第一種寫法
(function () {
// 函數(shù)體
})();
// 第二種寫法
(function () {
// 函數(shù)體
}());
箭頭函數(shù)的寫法
// 第一種寫法的箭頭函數(shù)形式(正確語(yǔ)法)
(() => {
// 函數(shù)體
})();
// 第二種寫法的箭頭函數(shù)形式(錯(cuò)誤語(yǔ)法)
(() => {
// 函數(shù)體
}());
接收立即執(zhí)行函數(shù)的返回值
const res = function (...params) {
return params
}('html', 'css', 'js');
const res = ((...params) => {
return params
})('html', 'css', 'js');