📅  最后修改于: 2023-12-03 15:15:48.110000             🧑  作者: Mango
An Immediately Invoked Function Expression (IIFE) is a function that is called immediately after it is defined. The main advantage of using an IIFE in JavaScript is to create a new scope for variables, which helps to prevent polluting the global namespace.
(function () {
//code to be executed
})();
The above code defines a function and invokes it immediately.
Let's look at an example that uses IIFE to define a module.
var module = (function () {
var count = 0;
function incrementCount() {
count++;
console.log('Count:', count);
}
return {
increment: incrementCount
};
})();
module.increment(); // Output: Count: 1
In the above example, we define a module using IIFE. The module has a private variable count
and a public function increment
. The increment
function increments the count
variable and logs it to the console.
The module is immediately invoked and its return value is stored in the module
variable. We can then use the increment
function to increment the count
variable.
IIFE is a useful feature in JavaScript to create new scopes for variables and prevent polluting the global namespace. It can be used to define modules, which helps to encapsulate the implementation details and make the code more modular.