● 클로저
클로저란 내부함수가 외부함수의 컨텐스트에 접근할 수 있는 것을 가르킨다.
- 쉽게 설명하면 함수 내에서 함수를 정의하고 사용하면 클로저라고 한다.
- 클로저는 외부함수의 지역변수, 인자 등을 외부함수가 종료된 이후에도 사용이 가능한다. 이러한 변수를 자유변수라고 한다.
소스코드로 살펴보면 다음과 같다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closure() { | |
var x = '클로저' | |
return function() { | |
return x | |
} | |
} | |
var test = closure() | |
console.log(test()) |
클로저
위 코드를 살펴보면 closure() 는 함수를 반환하고, 반환된 함수는 closure() 내부에서 선언된 변수를 참조하고 있다. 이렇게 참조된 변수는 함수 실행이 끝나도 사라지지 않고 여전히 옳바른 값을 반환하는 것을 알 수 있다.
● 클로저를 통한 은닉화
클로저를 사용하면 외부에서 변수에 직접 접근하는 것을 제한할 수 있다. 즉 변수를 객체지향의 private 처럼 사용할 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closure(name) { | |
return { | |
getName: function () { | |
return name | |
}, | |
setName: function (_name) { | |
name = _name | |
} | |
} | |
} | |
var test1 = closure('Jay') | |
var test2 = closure('Roy') | |
console.log(test1.getName()) | |
console.log(test2.getName()) | |
test1.setName('Micky') | |
console.log(test1.getName()) |
Jay
Roy
Micky
● 클로저를 통한 반복문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var test = [] | |
for (var i = 0; i < 3; i++) { | |
test[i] = function () { | |
return i | |
} | |
} | |
for (var index in test) { | |
console.log(test[index]()) | |
} |
3
3
3
출력을 하는 시점에서 i의 값은 5이기 때문에 0 1 2 가 아니라 3만 출력이 된다.
● 클로저의 성능
클로저는 각각의 자유변수를 계속 참조하기때문에 메모리가 소모된다. 따라서 클로저 사용이 끝나면 참조를 제거해야한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closure(name) { | |
return { | |
getName: function () { | |
return name | |
}, | |
setName: function (_name) { | |
name = _name | |
} | |
} | |
} | |
var test1 = closure('Jay') | |
var test2 = closure('Roy') | |
console.log(test1.getName()) | |
console.log(test2.getName()) | |
test1.setName('Micky') | |
console.log(test1.getName()) | |
test1 = null | |
test2 = null |
'웹 프로그래밍 > JavaScript' 카테고리의 다른 글
[JavaScript] 파도 효과 구현하기 (0) | 2021.10.07 |
---|---|
[JavaScript] 무한 스크롤 구현하기 (0) | 2021.09.26 |
[JavaScript] - var, let, const (0) | 2021.08.30 |
[JavaScript] - 호이스팅(Hoisting) (0) | 2021.08.26 |