본문 바로가기

미드영어 공부

Javascript 클로저 ( closure )

JAVASCRIPT CLOSURE



Javascript를 사용하거나 배우고 있는 분들은 아마 클로저(closure)라는 말을 한번쯤 들어 보셨을 겁니다.


클로저에 대한 한글 정의는 아래와 같습니다.


클로저는 독립적인 (자유) 변수 (지역적으로 사용되지만, 둘러싼 범위 안에서 정의된 변수)를 참조하는 함수들이다. 다른 말로 하면, 이 함수들은 그들이 생성된 환경을 '기억'한다. - 출처


클로저를 사용하면 정의에 나와 있듯이 어떤 것을 기억시킬 수 있습니다.


클로저(closure) 예제 1


1
2
3
4
5
6
7
8
function multiply(a){
    return function(b) {
      return a*b;
  }
}
 
const mutiplyByTwo = multiply(2);
console.log(mutiplyByTwo)
cs


결과 - 함수를 리턴 합니다.


1
2
3
function (b) {
      return a*b;
  }
cs


그리고 mutiplyByTwo 함수를 실행 시키면 결과 값은 8!


1
console.log(mutiplyByTwo(4))
cs



multiply(2)를 실행시키면 먼저 multiply 함수가 메모리에 올라가게 됩니다.

그리고 그 안에는 a(2)도 포함되어 있죠.

하지만 함수가 종료되면 multiply 함수는 메모리에서 없어지지만 a(2)는 메모리상에 남아 있게 되고

나중에 mutiplyByTwo 함수를 실행시킬 때 a를 현재 scope가 아닌 밖에서 찾아보게 됩니다 (scope chain).


클로저(closure) 예제 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
26
27
28
29
30
31
32
33
function Model(namespace, table) {
    state = {
      namespace: namespace,
     table: table
  }
  
  return {
      save: save(state),
    getById: getById(state)
  }
}
 
function save(state) {
    return function (data) {   
          return console.log(`Save data: ${data} into ${state.namespace}.${state.table}`);
  }
}
 
function getById(state) {
    return function (id) {
          return console.log(`Find id :${id}, from : ${state.namespace}.${state.table}`);
  }
}
 
//모델에 namespace와 table 값을 전달 합니다.
//그 값든은 Model이라는 함수가 기억하게 되죠
//state는 메모리 상에 존재 하게 되고 그것을 scope chain이라는 방법을 통해 접근 하게 됩니다.
var googleModel = Model('google', 'search');
var testModel = Model('test','search');
 
googleModel.save({id: 12, concept: 'closure'});
googleModel.getById(12);
 
testModel.save({id: 3, concept: 'composition'});
testModel.getById(3);
cs


save 함수를 아래와 같이 리턴 할 수도 있습니다.


1
2
3
4
5
6
return {
      save: function (data) {
        console.log(`Save data: ${data} into ${state.namespace}.${state.table}`);
    },
    getById: getById(state)
}
cs


실행 결과


1
2
3
4
Save data: [object Object] into google.search
Find id :12, from : google.search
Save data: [object Object] into test.search
Find id :3, from : test.search
cs



이상으로 클로저에 대한 설명을 마치겠습니다.