function outerFunc() {
var x = 10;
var innerFunc = function () { console.log(x); };
innerFunc();
}
outerFunc();
function outerFunc() {
var title = 'coding funny';
return function() {
alert(title);
}
}
innerFunc = outerFunc();
innerFunc
내부함수
는 외부함수의 실행이 끝나서 외부함수가 소멸된 이후에도 내부함수가 외부함수의 변수에 접근할 수 있다.innerFunc
는 outerFunc
를 호출하고 있다. outerFunc
는 실행이 끝났기 때문에 지역변수는 소멸되는 것이 자연스럽다. 하지만 실제 실행결과를 보면 'coding funny'가 출력되는 것을 볼수 있다. 즉, 외부함수는 외부함수의 지역변수를 사용하는 내부함수가 소멸될 때까지 소멸되지 않는 특성을 의미한다.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()); //'Ghost in the shell'
alert(matrix.get_title()); //'Matrix'
ghost.set_title('공각기동대');
alert(ghost.get_title()); //'공각기동대'
alert(matrix.get_title()); //'Matrix'
factory_movie
는 객체를 return한다. 이 객체는 메소드 get_title
, set_title
을 가지고 있다. 메소드는 지역변수 title
을 사용하고 있다.ghost.set_title('공각기동대');
는 title의 값을 '공각기동대'로 변경했다. ghost.get_title()
에서 '공각기동대'가 나오는 것은 title을 공유하고 있기 때문이다.클로저를 공부하다보니 React의 useState와 비슷하다는 생각을 하게 되었다.
클래스형 컴포넌트
와 달리함수형 컴포넌트
는 렌더가 필요할 때마다 함수를 다시 호출한다.함수형 컴포넌트
는 props를 인자로 받아 jsx문법에 맞는 리액트 컴포넌트를 리턴하는 것이 함수형 컴포넌트이다. 함수형 컴포넌트
에서 상태관리를 하기 위해서는 함수가 다시 호출되었을 때 이전의 상태를 기억하고 있어야 하는데 React Hook은 클로저를 통해서 해결하려 한다.const customUseState = (initialVal) => {
let innerState = initialVal;
const state = () => innerState;
const setState = (newVal) => {
innerState = newVal;
};
return [state,setState];
}
const [Counter,setCounter] = customUseState(0);
console.log(Counter);
setCounter(1);
console.log(Counter)
😘 useState원리에 대한 내용은 다음에 useState만의 포스트를 게시하겠습니다.
참고)
https://opentutorials.org/course/743/6544
https://yeoulcoding.tistory.com/149