웹개발/혼자하는 개발 공부

[자바스크립트] IIFE (Immediately Invoked Function Expressions)

데브리 2021. 9. 16. 04:51

 

정의됨과 동시에 즉시 실행되는 함수.

 

IIFE creates a function but not even having to save it somewhere. 

단 한번만 쓰고 없어지는 function이 필요할 때가 있는데, 예를 들면 async/await

 

 

(function () {
    console.log('한번만 쓸 function');
});


또는


(() => console.log('한번만 쓸 function'))();

statement 전체를 ( )로 감싸서 expression으로 바꾼다. 

 

 

 

 

 

 

 

왜 IIFE가 필요한가?

 

One scope does not have access to variables from an inner scope. All data defined inside a scope is provate (this data is encapsulated 압축, 요약되다).

 

 

 

*Data encapsulation

 

* Data encapsulation and data privacy are extremely important concepts in programming. So many times we need to protect our variables. It is important to hide our variables. 

 

 

 

 

 

 

더 공부하실 분들은 MDN에서 

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

 

IIFE - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.

developer.mozilla.org