📜  iife - Javascript (1)

📅  最后修改于: 2023-12-03 15:15:48.110000             🧑  作者: Mango

IIFE in JavaScript

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.

Syntax
(function () {
  //code to be executed
})();

The above code defines a function and invokes it immediately.

Example

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.

Advantages
  • IIFE helps to prevent polluting the global namespace.
  • It creates a new scope for variables, which helps to avoid conflicts between different parts of the code.
  • It can be used to define modules and encapsulate the implementation details.
Conclusion

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.