자바스크립트 즉시 실행 함수 패턴 (Immediately Invoked Function Pattern)

In JavaScript, the Immediately Invoked Function Pattern (IIFE) is a design pattern that allows you to create a self-executing anonymous function. It provides a way to execute JavaScript code immediately after it’s defined, without any explicit function call.

Why use the Immediately Invoked Function Pattern?

The IIFE pattern is commonly used in JavaScript for several reasons:

  1. Encapsulation: By wrapping your code inside an IIFE, you create a new scope, preventing variable and function name conflicts with other parts of your code or external libraries.

  2. Data Privacy: The variables and functions inside the IIFE are not accessible from the outside, providing a way to create private variables and encapsulate logic within the function.

  3. Module Pattern: The IIFE pattern can be used to implement the Module pattern, allowing you to create modules with private members and expose a public API.

Syntax of the Immediately Invoked Function Pattern

The basic syntax for an IIFE is as follows:

(function() {
   // code goes here
})();

The above code defines an anonymous function and immediately invokes it by adding parentheses at the end. Any code placed inside the function will be executed right away.

Example Usage

Let’s see an example where we use the IIFE pattern to encapsulate a piece of code:

(function() {
  var message = "Hello, I'm inside an IIFE!";
  console.log(message);
})();

In this example, we define an anonymous function and immediately invoke it. Inside the function, we have a variable message which is logged to the console. By using the IIFE pattern, the message variable is encapsulated and cannot be accessed outside the function.

Passing Parameters to IIFE

An IIFE can also accept parameters just like any other function. Let’s modify our previous example to accept a parameter:

(function(name) {
  var message = "Hello, " + name + "! I'm inside an IIFE!";
  console.log(message);
})("John");

In this updated example, we pass the parameter “John” to the IIFE when invoking it. The parameter name is used to construct the message logged to the console.

Conclusion

The Immediately Invoked Function Pattern is a powerful tool in JavaScript for creating encapsulated code, preventing variable conflicts, and implementing the Module pattern. By leveraging the IIFE pattern, you can write cleaner, more organized, and more secure JavaScript code.