1. IIFE ( Immediately Invoked Function Expressions )



자바스크립트에서 즉시 호출되는 익명 함수 표현식을 말한다.



1.1 일반적으로 함수를 선언하는 방식


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 1. The natural function definition
function sayHi() {
    console.log("Hello, World!");
}
sayHi(); // shows "Hello, World!" as console log in browser.
 
// 2. Function expressions
var msg = "Hello, sanghyun!";
var sayHi2 = function() {
    console.log(msg);
};
sayHi2(); // shows msg as console log in browser.
 
// 3. Named function expressions
var fibo = function fibonacci() {
    // you can use "fibonacci()" here as this funciton expression has a name.
};
// fibonacci() here fails, but fibo() works.
cs


함수를 선언 생성하고 함수명을 호출하는 방식을 사용한다.




1.2 execute once IIFE, void IIIFE, return value IIFE 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 4. That’s a function that died immediately after it came to life.
!function() {
    console.log("Hello from IIFE!");
}();
// Shows the console log "Hello from IIFE!"
 
 
// 5. All the below patterns are useful when we are not interested in the return value from the IIFE.
void function() {
    console.log("void from IIFE!");
}();
 
// 6. IIFEs with a return value
var result = (function() {
    return "return value from IIFE";
}());
console.log(result); // console log "From IIFE"
cs




1.3 일반적인 IIFE의 여러가지 표현방식


1
2
3
4
5
6
7
8
9
10
// 7. Classical IIFE style
// Variation 1
(function() {
    console.log("I am an IIFE!");
}());
 
// Variation 2
(function() {
    console.log("I am an IIFE, too!");
})();
cs




1.4 유효한 IIFE와 무효한 IIFE


1
2
3
4
5
6
7
8
9
10
11
12
13
// 8. Valid IIFE
(function initGameIIFE() {
    // All your magical code to initalize the game!
    console.log("initGameIIFE");
}());
 
// 9. invalid IIFE
function nonWorkingIIFE() {
}();
 
function () {
    // You will get a syntax error here as well!
}();
cs


선언한 함수 전체를 감싸지 않는다면 무효하다.




1.5 IIFE 안의 내부함수와 내부변수의 사용


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 10. IIFEs and private variables
(function IIFE_initGame() {
    // Private variables that no one has access to outside this IIFE
    var lives;
    var weapons;
    
    init();
    console.log(lives);
    console.log(weapons);
    
    // Private function that no one has access to outside this IIFE
    function init() {
        lives = 5;
        weapons = 10;
    }
}());
cs




1.6 IIFE에 파라미터를 넘겨 호출


1
2
3
4
5
6
7
// 11. IIFEs with parameters
(function IIFE(msg, times) {
    for (var i = 1; i <= times; i++) {
        console.log(msg+i);
    }
}("shlee"5));
// shlee1, shlee2, shlee3, shlee4, shlee5
cs


function에 매개변수를 넘겨 for문으로 해당값이 잘 넘어갔는지 확인했다. 



2. Module pattern



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 12. Classical JavaScript module pattern
var Sequence = (function sequenceIIFE() {
    // Private variable to store current counter value.
    var current = 10;
    // Object that's returned from the IIFE.
    return {
        getCurrentValue: function() {
            return current;
        },
        getNextValue: function() {
            current = current + 10;
            return current;
        }
    };
}());
 
console.log(typeof Sequence); // console log "object"
console.log(Sequence.getNextValue()); // 20
console.log(Sequence.getCurrentValue()); // 20
cs



current값이 IIFE에 숨겨저 있으므로 클로저를 통해 액세스 할수 있는 함수 외에는 curret값을 수정하거나 액세스 할 수 없다.

private 클로저 scope를 만들기 위해 IIFE를 사용한다. ( almost all of them use an IIFE to create a private closure scope )



3. 소스코드



https://repl.it/@shlee0882/IIFE


'전체 > JS & Jquery' 카테고리의 다른 글

자바스크립트 PC, 모바일 감지, resize 하기  (0) 2019.09.20
JS Event Loop(이벤트 루프)  (2) 2019.04.26
JS 표현식(expressions)  (0) 2019.04.09
JS scope from function, collision avoidance  (0) 2019.04.09
JS ==, === 의 비교  (0) 2019.04.08

+ Recent posts