closure : 외부함수의 변수에 접근할 수 있는 내부함수를 일컫는다.
리턴값으로 객체를 소환하여 , 함수를 쓸 때, 외부함수를 실행하지 않고 내부함수만 실행하여, 변수의 값도 자기 자신이 가지고 있는 것을 말한다.
내부함수가 외부함수의 변수에 접근 할 수 있기 떄문에 , 함수를 소환했을 때 외부함수에 가지 않고 바로 내부함수 안에서 값을 쓸 수 있어서 시간을 절약할 수 있고, 코드도 줄일 수 있다,
function outer(){
function inner(){
}
}
function human(){
const name = "pudding";
function sayHi(){
console.log(`hi I am ${name}`);
}
function howYouFeel(){
console.log(`${name} is feeling good`);
}
sayHi();
howYouFeel();
}
human()을 실행하면 다음과 같은 결과가 나온다 .
hi I am pudding
pudding is feeling good
sayHi()와 howYouFeel() 둘다 똑같은 변수를 공유하고 있다. 즉 내부함수는 바깥 함수의 변수를 찾아가 쓰고 있다
파라메터를 넣는 경우
function human(n){
const name = "pudding";
function sayHi(){
console.log(`hi i am ${name}`
}
function sayHowYouFeel(){
console.log(`${name} is feeling good`);
}
sayHi();
sayHowYouFeel()
}
human("pudding")
hi i am pudding
pudding is feeling good
이것도 내부 함수가 바깥 함수의 변수를 찾아가 쓰고 있다
위의 두 예시는 , human()함수가 실행될 때 둘다 실행되버린다.
근데 저렇게 함수 안에 함수를 바로 실행하는 것말고 버튼을 클릭하면 sayHi()함수만 실행하고 싶은 경우도 있을 것이다.
return 으로 객체값을 던져주면 된다 (factory function)
function human(n){
const name = n
function sayHi(){
return `hi i am ${name}`;
}
function howYouFeel(){
return `hi ${name} is good`
}
return {
sayHi, howYouFeel
}
}
리턴값으로 객체 그 자체를 던져주기 때문에 human() 이라는 outer function은 쓰지 않고, 바로 sayHi()나 howYouFeel()이라는 함수를 쓴다.
즉, 리턴값으로 레퍼렌스 타입을 통해 해주면, inner function이 바로 행해지고, outer function은 사용하지 않는다.
outer function 인 human()이 가지고 있는 name도, inner function()인 sayHi()와 howYouFeel() 둘다 outer function을 가지않아도 name이라는 레퍼랜스를 가지고 있다.
const pudding = human("pudding");
pudding.sayHi(); // human(name)을 실행하는게 아니라 , sayHi()를 실행하는 것이다
pudding.howYouFeel();
옷사이즈 예시
이렇게 사이즈를 변경하면 번거럽다
document.getElementById("size-12").onclick=function(){
document.body.style.fontSize = "12px"
}
document.getElementById("size-12").onclick=function(){
document.body.style.fontSize = "14px"
}
document.getElementById("size-12").onclick=function(){
document.body.style.fontSize = "16px"
}
function을 하나 만들어 준다.
function clickHandler(size) {
return function(){
document.body.style.fontSize = `${size}px`
}
}
document.getElementById("size-12").onclick=clickHandler(12);
document.getElementById("size-12").onclick=clickHandler(14);
document.getElementById("size-12").onclick=clickHandler(16);
이것도 closure의 한예이다. inner function이 outer function의 레퍼랜스로서 바로 쓰고 있다
return 을 객체로 바로 해줬기 때문(함수도 객체다)
'Development (국비 복습 ) > JavaScript' 카테고리의 다른 글
입력창을 받는 alert인 prompt (0) | 2023.03.05 |
---|---|
-prototype 정리 (0) | 2023.03.02 |
구조분해할당 (0) | 2023.02.26 |
재귀함수(recursive call)이란? (0) | 2023.02.26 |
input안에 값넣으면 리스트 추가 (0) | 2023.02.24 |
댓글