IIFE (Call Function Expression Immediately) is JavaScript that executes as soon as it is defined.
(function () {
statements
})();
Copy the code
This is a design pattern called self-executing anonymous functions, and it has two parts.
The first part is an anonymous function enclosed in the parenthesis operator () that has its own lexical scope. This not only prevents outside access to variables in the IIFE, but also does not contaminate the global scope.
The second part uses () again to create an instant-execute function expression, where the JavaScript engine executes the function directly.
Example:
var result = (function () {
var name = "Barry";
returnname; }) ();// IIFE:
result; // "Barry"
console.log(name); //name is undefined
Copy the code
When a function becomes a function expression that executes immediately, the variables in the expression cannot be accessed externally.
Immediate execution function:
- You don’t have to name functions to avoid contaminating global variables
- The immediate-execution function forms a separate scope inside and can encapsulate private variables that cannot be read from the outside
- Encapsulation variable
To summarize: immediately executing a function forms a separate scope. We can encapsulate temporary or local variables to avoid contaminating global variables
Such as: Some code needs to execute only once, such as the need to display only one time, but the code also need some temporary variables, but after the initialization process, will never be used, if these variables as global variables, is not a good idea, we can use the immediate execution function to wrap all our code in it, the local scope Do not let any variables leak as global variables. Look at this code:
Current time: <span id="today"></span>
<script>
(function () {
var currentTime = document.getElementById("today");
var days = ["Sunday"."Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"];
var today = new Date(a);var year = today.getFullYear();
var month = today.getMonth() + 1;
var date = today.getDate();
var day = today.getDay();
var msg = year + "Year" + month + "Month" + date + "Day"+ days[day]; currentTime.innerHTML = msg; }) ()</script>
Copy the code
Of course, you can also use ES6’s block-level scope to solve this problem