스코프, 렉시컬 스코프, 클로저

정태민·2025년 1월 9일
0

전역 스코프

전역에서 선언된 변수는 모든 곳에서 접근 가능.

	function printGlobal() {
 	 console.log(globalVar); // 접근 가능
	}

지역 스코프

함수 내부에서 선언된 변수는 함수 내부에서만 접근 가능.

  function localScopeExample() {
    let localVar = "I am local";
    console.log(localVar); // 접근 가능
  }

  localScopeExample();
  console.log(localVar); // ReferenceError: localVar is not defined

블록 스코프

let과 const로 선언된 변수는 블록 {} 내부에서만 접근 가능.

  {
    let blockScoped = "I am block scoped";
    console.log(blockScoped); // 접근 가능
  }
  console.log(blockScoped); // ReferenceError: blockScoped is not defined
	

함수 스코프

블록 내부에서 선언되더라도 함수 전체에서 접근 가능합니다.

	function functionScopeExample() {
    	if (true) {
      	  var functionScoped = "I am function scoped";
      	}
      	console.log(functionScoped); // 접근 가능
    	}

    functionScopeExample();
    console.log(functionScoped); // ReferenceError: functionScoped is not defined

스코프 체인

자바스크립트에서 변수의 접근은 단방향입니다.
아래에서 위로 스코프를 차례로 접근합니다.

	let globalVar = "global";

    function outer() {
      let outerVar = "outer";

      function inner() {
        let innerVar = "inner";
        console.log(innerVar); // "inner"
        console.log(outerVar); // "outer" (상위 스코프에서 찾음)
        console.log(globalVar); // "global" (전역 스코프에서 찾음)
      }

      inner();
    }

    outer();

렉시컬 스코프 (정적 스코프)

함수가 정의된 위치에 따라 스코프가 결정됨.

	let x = 1;
 	function foo() {
      var x = 2;
    	bar();
    }
	function bar() {
     console.log(x); 
    }
	foo(); // "1"	

동적 스코프

함수가 호출 된 위치에 따라 스코프가 결정됨. 자바스크립트에선 호이스팅 때문에 변수의 선언이 동적스코프처럼 보일수 있으나 변수의 유효 범위는 항상 선언된 위치에 따라 결정된다.

	let x = 1;
 	function foo() {
      var x = 2;
    	bar();
    }
	function bar() {
     console.log(x); 
    }
	foo(); // "동적 스코프라면 함수가 호출 되었을때 x는 2이므로 2를 출력해야한다."	

클로저

클로저는 함수와 그 함수가 선언된 환경(스코프)을 함께 기억하는 특성

  function cubic(A, B, C) {
    return (x) => (x * x * x) + A * (x * x) + B * x + C;
  }

  // 클로저 생성 
  const cubicFunction = cubic(1, 2, 3); // A=1, B=2, C=3 고정
  console.log(cubicFunction(2)); // 2^3 + 1*2^2 + 2*2 + 3 = 17 - 함수는 자신의 외부함수에 선언된 변수에 접근 할 수 있게된다.
	

커링

커링은 다중 매개변수를 갖는 함수를 단일 매개변수를 갖는 함수들의 체인으로 변환하는 기술 . 코드의 재사용성이 증가되며, 지연 평가가 가능하다.

	
function cubicCurried(A) {
  return (B) => {
    return (C) => {
      return (x) => (x * x * x) + A * (x * x) + B * x + C;
    };
  };
}

const cubicWithA1 = cubicCurried(1); // A=1 고정
const cubicWithA1B2 = cubicWithA1(2); // B=2 고정
const cubicWithA1B2C3 = cubicWithA1B2(3); // C=3 고정

console.log(cubicWithA1B2C3(2)); // 2^3 + 1*2^2 + 2*2 + 3 = 17

0개의 댓글