클로저 : 어떤 함수에서 선언한 변수를 참조하는 내부함수를 외부로 전달항 경우 함수의 실행 컨텍스트가 종료된 후에도 해당 변수가 사라지지 않은 현상
const outer = function(){
let a = 1
let inner = function(){
return ++a
}
return inner
}
const outer2 = outer()
console.log(outer2) // 2
console.log(outer2) // 3
그 이유는 가비지 컬렉터의 동작 방식 때문입니다. 가비지 컬렉터는 참조하는 변수가 하나라도 있다면 그 값은 수집 대상에 포함시키지 않습니다.
클로저와 메모리 관리
클로저는 어떤 필요에 의해 의도적으로 함수의 지역변수를 메모리를 소모하도록 함으로써 발생합니다. 즉 그 필요성이 사라진 시점에 메모리를 소모하지 않게 해주면 된다.
참조 카운트를 0으로 만들면 GC가 수거해가는데 참조 카운트를 0만드는 방법은 식별자에 null이나 undefined를 할당하면 됩니다.
const outer = (function(){
let a = 1
const inner = function(){
return ++a
}
return inner
})()
console.log(outer())
console.log(outer())
outer = null // 식별자의 inner함수 참조를 끊음
접근 권한 제어(정보 은닉)
어떤 모듈의 내부 로직에 대해 외부로의 노출을 최소화해서 모듈간의 결합도를 낮추고 유연성을 높이고자 하는 현대 프로그래밍 언어의 중요한 개념
class Experiment {
publicField = 2; // 그냥 정의하면 public
#privaterField = 0; // #(해쉬) 기호를 붙이면 private
}
const experiment = new Experiment();
console.log(experiment.publicField); // > 2 : 접근 가능
console.log(experiment.privaterField); // > undefined : 접근 불가능
최근에는 private같은 기능을 하는 #이 추가 되었습니다.
클로저를 이용하여 만들 수 도 있습니다.
const outer = function(){
let a = 1
const inner = function(){
return ++a
}
return inner
}
const outer2 = outer()
console.log(outer2())
console.log(outer2())
외부에 제공하고자 하는 정보들을 모아서 return하고 내부에서만 사용할 정보들은 return 하지 않는 것으로 접근 권한 제어가 가능합니다. return한 변수들은 공개 멤버(public member)가 되고, 그렇지 않은 변수들은 비공개 멤버(private member)가 됩니다.
const car = {
const fuel = Math.ceil(Math.random() * 10 + 10),
const power = Math.ceil(Math.random() * 3 + 2),
const moved = 0,
return{
get moved(){
return moved
}
run: function(){
const km = Math.ceil(Math.random() * 6)
const wasteFuel = km / this.power
if(this.fuel < wasteFuel){
console.log('이동불가')
return
}
this.fuel -= wasteFuel
this.moved += km
console.log(km + 'km 이동 (총 '+ this.moved + 'km)')
}
}
}
부분 적용 함수
n개의 인자를 받는 함수에 미리 m개의 인자만 넘겨 기억시켰다가 나중에 (n-m)개의 인자를 넘기면 원래 함수의 실행 결과를 얻을 수 있게 해주는 함수
부분 적용 함수는 스크롤 scroll, wheel, mousemove, resize 등에 적용하기 좋습니다.
const debounce = function(eventName, func, wait){
const timeoutId = null
return function(event){
const self = this
console.log('event', eventName)
clearTimeout(timeoutId)
timeoutId = setTimeout(func.bind(self, event), wait)
}
}
const moveHandler= function(e){
console.log('move event 처리')
}
const wheelHandler = function(e){
console.log('wheel event 처리')
}
document.body.addEventListener('mousemove', debounce('move', moveHandler, 500))
document.body.addEventListener('mousewheel', debounce('wheel', wheelHandler, 700))
커링 함수
여러개의 인자를 받는 함수를 하나의 인자만 받는 함수로 나눠서 순차적으로 호출될 수 있게 체인 형태로 구성한 것을 말합니다.
한번에 하나의 원자만 전달하는 것을 원칙
마지막 인자가 전달되기 전까지는 원본 함수가 실행되지 않습니다.
const getInformation = function(baseUrl){ // 서버에 요청할 주소의 기본 URL
return function(path){ // path 값
return function(id){ // id 값
return fetch(baseUrl + path + '/' + id) // 실제 서버에 정보를 요청
}
}
}
// ES6
const getInformation = baseUrl => path => id => fetch(baseUrl + path + '/' + id)
const imageUrl = 'http://imageAddress.com/'
const getImage = getInformation(imageUrl) // http://imageAddress.com/
const getEmoticon = getImage('emoticon') // http://imageAddress.com/emoticon
const getIcon = getImage('icon') // http://imageAddress.com/icon
'it 책 > 코어 자바스크립트' 카테고리의 다른 글
7장 클래스 (0) | 2022.05.20 |
---|---|
6장 프로토 타입 (0) | 2022.05.12 |
3장 this 정리 (0) | 2022.05.03 |
2장 실행 컨텍스트 (0) | 2022.05.02 |
1장 정리 (0) | 2022.05.01 |