728x90
this 키워드란?
- 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수
- this가 가리키는 과정을 바인딩(binding)이라고 한다.
- 엄격모드 여부/함수의 호출 방식/this 값이 결정되는 상황에 의해 동적으로 결정되게 된다.
this를 가리키는 값이 결정되는 경우
- 전역 실행 컨텍스트: → 전역 실행 컨택스트 (windows 객체 혹은 undefined)
- 비엄격모드
console.log(this); // 브라우저에서는 window 객체 - 엄격모드
console.log(this); // undefined
- 비엄격모드
- 함수 호출: 일반 함수에서
this→ 함수 내에서의 컨텍스트에 따라 다름- 비엄격모드
function regularFunction() { console.log(this); // window 또는 global 객체 } regularFunction(); - 엄격모드
function strictFunction() { 'use strict'; console.log(this); // undefined } strictFunction();
- 비엄격모드
- 객체 메서드 내에서의
this→ 해당 메서드를 호출한 객체const obj = { name: 'JavaScript', getName: function() { console.log(this.name); } }; obj.getName(); // 'JavaScript' - 생성자 함수에서의
this: 새로 생성되는 객체- 비엄격모드
function Constructor() { this.property = "value"; } // new 없이 호출하면 전역 객체에 property 추가 Constructor(); // window.property = "value" - 엄격모드
"use strict"; function Constructor() { this.property = "value"; // TypeError: Cannot set property 'property' of undefined } Constructor(); // this가 undefined이므로 에러 발생
- 비엄격모드
- 이벤트 핸들러에서의
this: 이벤트를 받는 요소document.getElementById('myButton').addEventListener('click', function() { console.log(this); // 클릭된 버튼 요소 });
화살표 함수에서의 this의 특성
- 함수가 생성된 시점의 실행 컨텍스트의 this를 상속 받음
- 예시 코드
- regularFunction의 setTimeout 콜백 함수는 일반 함수로서 호출되어 전역 객체의 this를 가리킴
- arrowFunction의 setTimeout 콜백 함수는 화살표 함수로 정의되어 arrowFunction의 실행 컨텍스트인 obj의 this를 상속 받음
const obj = { name: 'JavaScript', regularFunction: function() { setTimeout(function() { console.log(this.name); // undefined (전역 객체의 name 속성) }, 100); }, arrowFunction: function() { setTimeout(() => { console.log(this.name); // 'JavaScript' }, 100); } }; obj.regularFunction(); obj.arrowFunction();
참고자료
728x90
'웹프로그래밍 > 부트캠프 - Codeit' 카테고리의 다른 글
| [5주차] 위클리 페이퍼 - React가 렌더링 하는 방식을 설명하세요. (1) | 2025.07.23 |
|---|---|
| [4주차] 위클리 페이퍼 - 렉시컬 스코프(Lexical Scope)의 개념과 그 특성에 대해 설명해 주세요. (2) | 2025.07.21 |
| [3주차] 위클리 페이퍼 - var, let, const 를 서로 비교해 설명해 주세요. (0) | 2025.07.15 |
| [3주차] 위클리 페이퍼 - 브라우저가 어떻게 동작하는지 설명해 주세요. (2) | 2025.07.08 |
| [2주차] 위클리 페이퍼 - DNS에 대해서 설명해 주세요. (0) | 2025.07.04 |