본문 바로가기

프로그래밍/자바스크립트

[자바스크립트] 내부 함수, 클로저

1. 내부 함수

- 함수 내부에 선언된 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>내부 함수</title>
<script type="text/javascript">
    function a(){
        //내부 함수
        function b(){
            document.write('b is called<br>');
        }
        
        //내부함수 호출
        b();
    }
    //함수 호출
    a();
    
    document.write('---------------------<br>');
    
    function c(){
        var n = 123;
        function d(){
            document.write('n is ' + n + '<br>');
            document.write('d is called<br>');
        }
        
        //내부 함수 호출
        d();
    }
    //함수 호출
    c();
    
    document.write('---------------------<br>');
    
    function f(){
        var n = 123;
        function g(){
            document.write('n is ' + n + '<br>');
            document.write('g is called');
        }
        return g; //내부함수 반환
    }
    
    //함수 호출
    var m = f();
    document.write(m+'<br>');    //함수의 정보가 모두 나옴
    document.write('---------------------<br>');
    
    //함수 호출
    m();
</script>
//출력 결과
b is called
---------------------
n is 123
d is called
---------------------
function g(){ document.write('n is ' + n + '
'); document.write('g is called'); }
---------------------
n is 123
g is called
</head>
<body>
</body>
</html>
</html>
cs

 

2. 클로저

- 지역변수를 남겨두는 현상
- 지역변수는 함수가 실행될 때 생성되고, 함수가 종료될 때 사라진다.
- 하지만 클로저 사용 시 이 규칙을 위반 할 수 있음

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>클로저</title>
<script type="text/javascript">
function outerFunction(name){
    //변수 선언 및 초기화
    var output = 'Hello ' + name + '..!';
    //내부 함수에서 지역변수를 사용하므로 지역변수를 남겨둠(클로저)
    return function(){
        //경고창으로 출력
        alert(output);
    }
}
 
var message = outerFunction('홍길동');
message();
</script>
//출력 결과
Hello 홍길동 ..!
</head>
<body>
</body>
</html>
cs