자율 학습/학습

[JavaScript] this의 범위 (this 지정 방법)

2022. 9. 29. 14:36

this = window (기본)

 

바뀌는 경우

1. 객체 메서드 안에서 this = 객체

2. this를 바꾸는 함수 셋 : blind, call, apply 사용

3. new생성자 함수 호출 시 this = 생성자를 통해 생성된 인스턴스

 

 


4. 이벤트 리스너 / jQuery 사용 시 내부적으로 this가 바뀐다.

$('div').on('click', function() {
  console.log(this);  // <div>
});

하지만 기본적으로 this는 window를 가리키기 때문에 아래와 같은 예시에서 this는 다시 window를 가리키게 됨.

$('div').on('click', function() {
  console.log(this); // <div>
  function inner() {
    console.log('inner', this); // inner Window
  }
  inner();
});

 

 

- 해결 방법 1) 변수에 담아 사용하기

- 해결 방법 2) ES6 화살표 함수 사용하기

$('div').on('click', function() {
  console.log(this); // <div>
  const inner = () => {
    console.log('inner', this); // inner <div>
  }
  inner();
});

ES6 화살표 함수는 상위 함수의 this를 가져온다.

 

 

출처: https://www.zerocho.com/category/JavaScript/post/5b0645cc7e3e36001bf676eb