https://offbyone.tistory.com/135

* 자유 변수(free variable) 
- 함수가 종료된 후에도 사용할수 있는 변수
- 외부함수가 내부 함수를 리턴하고 이걸 함수 표현식으로 정의하면서 가능해짐

* 클로저
- 자유 변수를 가지는 코드

function makeGreeting(name) {
    var greeting = "안녕! ";

    return function() {
        console.log(greeting + name);
    };
}

//다음 g1, g2 가 클로저
var g1 = makeGreeting("홍길동");
var g2 = makeGreeting("김철수");

g1(); //안녕! 홍길동
g2(); //안녕! 김철수





//================
// 참고
* Lexical scoping
변수의 유효 범위 지정 (어휘적 범위 지정_Lexical scoping)
단어 "Lexical"은 유효 범위를 지정할 때 변수가 사용가능한 범위를 결정하기 위해 소스 코드 내에서 변수가 선언된 위치를 사용한다는 것을 의미

//================
// 참고
https://offbyone.tistory.com/135
https://chanlee.github.io/2013/12/10/understand-javascript-closure/
https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Closures

Posted by 코덴스

댓글을 달아 주세요