React 화살표 함수와 상위 스코프 개념

2024년 12월 17일 by 보험지식창고

    React 화살표 함수와 상위 스코프 개념 목차
반응형

1. 화살표 함수와 상위 스코프의 의미

화살표 함수는 자체적인 this를 가지지 않고, 자신을 감싸는 상위 스코프(부모 스코프)의 this를 상속받습니다.

  • 전통적인 함수(function)는 호출될 때 this가 동적으로 결정되지만,
  • 화살표 함수는 선언될 때의 **상위 스코프의 this**를 사용합니다.

 

2. 전통적인 함수와 화살표 함수의 this 차이

전통적인 함수: 동적 this

function Person() {
  this.name = "John";

  setTimeout(function () {
    console.log(this.name); // 출력: undefined (또는 브라우저에서는 window의 값)
  }, 1000);
}

new Person();
 

화살표 함수: 상위 스코프의 this

 
function Person() {
  this.name = "John";

  setTimeout(() => {
    console.log(this.name); // 출력: John
  }, 1000);
}

new Person();

 

3. 화살표 함수에서의 this 정리

결론

  • 화살표 함수는 this를 자신이 선언된 위치의 상위 스코프에서 가져옵니다.
  • 전통적인 함수와 달리 this가 동적으로 변경되지 않습니다.

 

정리 예제

const obj = {
  name: "React",
  regularFunction: function () {
    console.log(this.name); // this는 obj를 가리킴
  },
  arrowFunction: () => {
    console.log(this.name); // this는 상위 스코프(전역 객체)를 가리킴
  },
};

obj.regularFunction(); // 출력: React
obj.arrowFunction(); // 출력: undefined

 

 

4. 상위 스코프의 의미 확인

상위 스코프란?

  • 화살표 함수가 선언된 위치에서 감싸고 있는 함수 스코프전역 스코프입니다.

상위 스코프 예시

const globalName = "Global";

function outer() {
  this.name = "Outer";

  const arrowFunc = () => {
    console.log(this.name); // this는 outer 함수의 this
  };

  arrowFunc();
}

outer(); // 출력: Outer

상위 스코프에 따라 결정된 this

  • arrowFunc는 outer 함수 내부에서 선언되었기 때문에 **this는 outer 함수의 this**를 참조합니다.
  • 만약 outer 함수가 new 키워드로 생성된 경우, this는 해당 객체를 가리킵니다.
  •  

5. 화살표 함수에서 this를 사용하는 경우

화살표 함수는 다음과 같은 경우에 유용합니다:

  1. 콜백 함수에서 this를 유지하기 위해 사용
    class Timer {
      constructor() {
        this.seconds = 0;
      }
    
      start() {
        setInterval(() => {
          this.seconds++;
          console.log(this.seconds); // this는 Timer 객체를 가리킴
        }, 1000);
      }
    }
    
    const timer = new Timer();
    timer.start();
  2. 이벤트 핸들러에서 this를 유지하고 싶을 때
    const button = document.createElement("button");
    button.innerText = "Click me";
    button.onclick = () => {
      console.log(this); // 상위 스코프의 this (전역 객체 또는 부모 함수의 this)
    };
    document.body.appendChild(button);
     

정리

  • 화살표 함수의 상위 스코프는 **선언된 위치의 this**입니다.
  • 자체적인 this를 가지지 않기 때문에 상위 스코프에서 this를 가져와 사용합니다.
  • 전통적인 함수와의 차이를 명확히 이해하면 this를 혼동하지 않고 사용할 수 있습니다.
반응형

'IT' 카테고리의 다른 글

React 함수 선언 방법 2가지  (0) 2024.12.17
React의 State(상태)란?  (0) 2024.12.17
React 기초  (0) 2024.12.17
IP 주소 확인  (0) 2024.12.16
오라클 힌트  (0) 2024.12.13