본문 바로가기

Study Memos/JavaScript Basic

클로저 (Section 20)

참고> opentutorials.org/course/743/6544

 

1. 클로저 : 내부 함수가 외부 함수의 맥락(context)에 접근할 수 있는 것

2. 내부함수: 함수 내의 함수 중 안쪽에 있는 함수

3. 외부함수 : 함수 내의 함수 중 바깥쪽에 있는 함수

4. 내부 함수는 외부 함수의 지역 변수에 접근 가능

5. 클로저를 사용하면 private variable을 사용할 수 있음.
-> 내부 함수가 리턴될 때 각자의 맥락(context)을 가지기 때문.

ex)
function factory_movie(title){
    return {
        get_title : function (){
            return title;
        },
        set_title : function(_title){
            title = _title
        }
    }
}
ghost = factory_movie('Ghost in the shell');
matrix = factory_movie('Matrix');
 
alert(ghost.get_title());
alert(matrix.get_title());
 
ghost.set_title('공각기동대');
 
alert(ghost.get_title());
alert(matrix.get_title());

위의 출력 순서는
'Ghost in the shell' -> 'Matrix' -> '공각기동대' -> 'Matrix' 가 됨. (ghost와 matrix의 맥락이 별개임)

6. 클로저를 쓸 때 자주하는 실수
ex)
var arr = []
for(var i = 0; i < 5; i++){
    arr[i] = function(){
        return i;
    }
}
for(var index in arr) {

    console.log(arr[index]());

}

 

위와 같이 하면 arr에 저장된 모든 i가 5의 값을 가짐

외부 함수의 지역 변수를 내부 함수가 참조하게 만들어야 한다.
그래야 맥락(context)이 별도로 구분된다.

 

ex)
var arr = []
for(var i = 0; i < 5; i++){
    arr[i] = function(id) {
        return function(){
            return id;
        }
    }(i);
}
for(var index in arr) {

    console.log(arr[index]());

}

 

이렇게 해야 한다.

'Study Memos > JavaScript Basic' 카테고리의 다른 글

함수 호출 (Seciton 22)  (0) 2020.10.27
arguments(Section 21)  (0) 2020.10.27
값으로서의 함수와 콜백 (Section 19)  (0) 2020.10.27
유효 범위 (Section 18)  (0) 2020.10.27
함수 지향 (Section 17)  (0) 2020.10.27