WeniVooks

검색

JavaScript 베이스캠프

this

1. this 키워드 이해하기

JavaScript에서 this 키워드는 매우 중요하지만, 처음에는 이해하기 어려울 수 있습니다. this는 함수가 어떻게 호출되었는지에 따라 다르게 동작하기 때문입니다. 심지어 콘솔창과 위니북스의 this도 다르기 때문에 여기서는 콘솔창을 열어 실습해주시기 바랍니다.

this를 다른 언어처럼 '나 자신'이라고 한 마디로 정의할 수는 없으며 다양한 예외 케이스가 있어 '나 자신을 호출한 객체' 또는 '무엇' 이라고 정의 내리긴 어렵습니다. 앞서 말씀드린 것처럼 어떻게 호출되었는지에 따라 다르게 동작하기 때문입니다. 그럼에도 불구하고 this를 한 마디로 정의하자면 '함수가 호출되는 방식에 따라 달라지는 특수한 키워드'라고 할 수 있습니다.

다양한 상황을 통해 this가 가리키는 값을 살펴보겠습니다.

1. 전역 범위 호출
console.log(this); // 브라우저에서는 window 객체
console.log(this); // 브라우저에서는 window 객체

전역 범위, 보통 전역 컨텍스트라고 얘기합니다. 전역 컨텍스트에서 this는 전역 객체를 가리킵니다. 브라우저에서는 window 객체가 전역 객체이며 Node.js 환경에서는 global 객체가 전역 객체입니다.

2. 함수 범위 호출

함수 내부에서 this의 값은 함수를 호출한 방식에 따라 결정됩니다.

2.1 일반 함수 호출

일반 함수 호출에서 this는 전역 객체를 나타냅니다.

function f() {
  console.log(this);
}
 
f(); // Window 객체 (브라우저에서)
function f() {
  console.log(this);
}
 
f(); // Window 객체 (브라우저에서)
2.2 화살표 함수 호출

화살표 함수에서 this는 함수가 정의된 위치의 컨텍스트를 유지합니다. 이를 "lexical this"라고 합니다.

const obj = {
  f: function () {
    const ff = () => {
      console.log(this);
    };
    ff();
 
    const fff = function () {
      console.log(this);
    };
    fff();
  },
};
 
obj.f();
// f (화살표 함수 ff에서의 this)
// Window 객체 (일반 함수 fff에서의 this)
const obj = {
  f: function () {
    const ff = () => {
      console.log(this);
    };
    ff();
 
    const fff = function () {
      console.log(this);
    };
    fff();
  },
};
 
obj.f();
// f (화살표 함수 ff에서의 this)
// Window 객체 (일반 함수 fff에서의 this)
2.3 메서드 호출

객체의 메서드로 호출된 함수에서 this는 해당 객체를 나타냅니다.

const obj = {
  name: 'licat',
  f: function () {
    console.log(this);
  },
};
 
obj.f(); // obj
const obj = {
  name: 'licat',
  f: function () {
    console.log(this);
  },
};
 
obj.f(); // obj
2.4 생성자 함수 호출

new 키워드를 사용하여 생성자 함수를 호출하면, this는 새로 생성된 객체를 나타냅니다.

function Person(name) {
  this.name = name;
  console.log(this);
}
 
const person1 = new Person('licat'); // Person { name: "licat" }
const person2 = new Person('mura'); // Person { name: "mura" }
const value = Person('test'); // Window 객체를 출력하고 undefined를 반환
function Person(name) {
  this.name = name;
  console.log(this);
}
 
const person1 = new Person('licat'); // Person { name: "licat" }
const person2 = new Person('mura'); // Person { name: "mura" }
const value = Person('test'); // Window 객체를 출력하고 undefined를 반환

3. 이벤트 헨들러 내에서 호출

이벤트 핸들러는 사용자나 브라우저의 특정 동작(이벤트)에 반응하여 실행되는 함수입니다. '핸들러 함수'라고도 불립니다. 자주 등장하는 용어이니 용어를 알아두시기 바랍니다.

웹 페이지에서 자주 사용되는 이벤트에는 클릭, 키보드 입력, 마우스 이동 등이 있습니다. 이벤트 핸들러는 주로 addEventListener 메서드를 사용하여 특정 요소에 할당됩니다.

이벤트 핸들러 내에서 this는 이벤트가 발생한 DOM 요소를 가리킵니다. 아래 예제는 직접 html 파일에 작성해보세요.

<button id="btn">hello world!</button>
 
<script>
const button = document.getElementById('btn');
button.addEventListener('click', function() {
  console.log(this); // <button id="btn">Click me!</button>
});
</script>
<button id="btn">hello world!</button>
 
<script>
const button = document.getElementById('btn');
button.addEventListener('click', function() {
  console.log(this); // <button id="btn">Click me!</button>
});
</script>
4. 실무에서 자주 등장하는 this

실무에서는 이벤트 핸들러에서 this를 많이 사용합니다. 이벤트 핸들러에서 this는 이벤트가 발생한 요소를 가리킵니다. 다음은 체크박스를 클릭할 때마다 배경색이 바뀌는 예제입니다. html 파일을 생성하여 아래 예제를 실행해보세요.

<!DOCTYPE html>
<html>
  <body>
    <input type="checkbox" id="checkbox" /> 체크해보세요.
 
    <script>
      const checkbox = document.getElementById('checkbox');
      checkbox.addEventListener('change', function () {
        if (this.checked) {
          document.body.style.backgroundColor = 'lightblue';
        } else {
          document.body.style.backgroundColor = '';
        }
      });
    </script>
  </body>
</html>
<!DOCTYPE html>
<html>
  <body>
    <input type="checkbox" id="checkbox" /> 체크해보세요.
 
    <script>
      const checkbox = document.getElementById('checkbox');
      checkbox.addEventListener('change', function () {
        if (this.checked) {
          document.body.style.backgroundColor = 'lightblue';
        } else {
          document.body.style.backgroundColor = '';
        }
      });
    </script>
  </body>
</html>

this는 중급자로 넘어가기 전에 정리를 한 번 더 해야합니다.

여기서 다루고 있는 this가 전부가 아닙니다. this는 더 다양한 활용 사례가 있으며 예외 사항도 있습니다. 또한 이 강의가 초급자 강의이기 때문에 call(), apply(), bind() 메서드를 사용하여 this의 값을 명시적으로 설정할 수 있는 방법에 대해서 다루지 않았습니다. 자바스크립트에 대해 더 깊이 공부하고 싶다면 이 부분을 찾아보시기 바랍니다.

6장 조금 더 깊이 들여다보기6.2 반복문(for in과 for of)