자바스크립트에서 렉시컬은 자바스크립트가 코드를 해석할 때, 변수나 함수가 정의된 위치를 기준으로 변수가 어디까지 유효한지를 결정하는 개념입니다.
렉시컬 스코핑은 함수가 어디서 호출되었는지가 아니라, 함수가 어디서 정의되었는지에 따라 그 함수가 접근할 수 있는 변수가 결정된다는 것입니다.
function outerFunction() {
let outerVariable = '밖에 있는 변수'; // outerFunction 안에서만 접근 가능
function innerFunction() {
console.log(outerVariable); // innerFunction 내부에서 outerVariable에 접근 가능
}
innerFunction();
}
outerFunction(); // "밖에 있는 변수" 출력
outerFunction
내부에는 outerVariable
이라는 변수가 있습니다.innerFunction
은 outerFunction
안에서 정의된 함수이기 때문에, 렉시컬 스코핑에 의해 outerVariable
에 접근할 수 있습니다.정리하자면 innerFunction
은 outerFunction
안에서 정의되었으므로, 그 정의된 위치에 따라 outerVariable
을 사용할 수 있게 됩니다.
호출된 위치와 상관없이, 자신이 정의된 스코프 안의 변수를 참조할 수 있는 것을 보여줍니다.
클로저(Closure)는 내부 함수가 외부 함수의 변수를 기억하고 그에 접근할 수 있는 기능을 의미하며, 자바스크립트의 매우 강력한 기능입니다.
렉시컬 스코핑 덕분에 클로저가 가능해집니다.
function outerFunction() {
let counter = 0; // 외부 변수
return function incrementCounter() {
counter++; // 외부 변수를 기억하고 접근
console.log(counter);
};
}
const counterFunction = outerFunction();
counterFunction(); // 1
counterFunction(); // 2
counterFunction(); // 3
여기서 incrementCounter
함수는 외부의 counter
변수를 기억하고 있어, outerFunction
이 종료된 후에도 counter
에 접근하고 값을 증가시킬 수 있습니다.