결론 빨리 알고 싶을 땐 정리 로 이동해서 보믄 된다
📌 그냥 쓸 때 : window
<script> 태그 안에 바로 this 를 쓰면 window를 뜻한다
📌 일반 함수 : window
window란?
window 는 모든 전역변수, 함수, DOM을 보관하고 관리하는 전역객체이다.
전역변수를 선언하면 window 객체에 저장된다.
함수도 마찬가지이다.
🔎 그냥 쓰거나, 함수 안에서의 this 는 window 를 뜻한다
📌 strict mode 일 때 함수 안에서의 this : undefined
strcit mode에선 var 키워드 없이 변수를 선언하거나, 변수를 arguments라는 키워드로 선언하거나 하는 실수들을 방지해준다.
📌 method(오브젝트 내의 함수) 안에서의 this : 해당 오브젝트 그 자체
sayHi 라는 메소드를 호출해보면
this 는 메소드를 가지고 있는 오브젝트를 뜻하는 것을 알 수 있다.
🔎 오브젝트 안의 함수를 메소드라고 한다
왼쪽에 obj 를 정의했다. 오른쪽 콘솔창의 결과물은 무엇일까?
메소드 안에서의 this 는 메소드가 가지고 있는 오브젝트라고 했으니 data란 object 가 출력된다.
즉 sayBye 메소드 안에서의 this = obj.data
앞에서 그냥 쓰거나, 일반 함수 내에서의 this 는 window 임을 알 수 있었다.
사실 메소드 안에서의 this 가 메소드를 가진 오브젝트라는 것을 알면 위의 내용은 암기할 필요가 없다.
window 도 하나의 오브젝트이다.
함수를 정의한다는 것 = window 라는 오브젝트 안의 메소드로 등록하는 것
메소드의 this ?
= 메소드를 가지고 있는 오브젝트
= window
그러니 메소드이 this 는 메소드를 포함한 오브젝트라는 것만 알면
script 에 바로 this 를 썼을 때와 일반 함수 안에서의 this 는 window 를 의미한다는 것을 자동으로 알 수 있다.
📌 constructor 에서의 this : 생성자함수를 통해 새로 생성될 오브젝트
자바스크립트에서 오브젝트를 비슷한 걸 여러개 만들고 싶을 경우에,
오브젝트를 복사하는 것이 아니라 constructor 라는 것을 만들어서 사용한다.
constructor = 오브젝트 복사하는 기계 라고 생각하면 편하다.
constructor 은 정의할 땐 함수 정의와 똑같다.
makePerson 이라는 함수를 만들었다.
이 함수를 일반함수처럼 호출하면 그냥 얘는 일반함수다
makePerson(); // 그냥 일반 함수
그럼 위에서 this 는 무엇이 출력될까?
window가 출력된다.
똑같은 함수를 new 키워드를 활용하여
new makePerson(); 으로 호출하면,
this 가 달라진 것을 확인할 수 있다.
생성자함수 안에서의 this 는 새로 생성될 오브젝트를 의미한다.
new 키워드를 이용하여 새로운 오브젝트를 생성했다!
makePerson 에 age 를 추가해서 생성자함수를 실행시켜보면 다음과 같다.
📌 eventlistener 안에서의 this : e.currentTarget 이라는 의미
e.currentTarget 은 지금 이벤트가 동작하는 곳을 뜻한다.
버튼을 클릭하여 this 를 클릭하면 e.currentTarget 과 같은 결과값이 출력됨을 알 수 있다.
🎵 이벤트리스너 안에서 콜백함수를 쓴다면 this 는? window
일반함수와 동일하게 this 가 출력된다.
🎵 오브젝트 안에서 콜백함수를 쓴다면 this 는? window
동일하게 콜백함수라는 일반함수 안에서의 this 이므로 window 가 출력된다.\
⚡ this 가 요래저래 바뀌는게 짜증난다? arrow function 쓰기!
나는 test 라는 메소드 안의 this 를 메소드를 가지는 오브젝트를 뜻하게 하고 싶다면 ?
arrow fucntion 을 이용하면 this 가 의도한 대로 출력된다.
📌 정리
1. 그냥 this / 일반함수 안에서의 this = window
2. 오브젝트 안의 함수(=메소드) 안에서의 this = 해당 메소드를 가진 오브젝트 그 자체
* strict mode 에서의 일반 함수 안에서 this 는 undefined
3. 생성자함수(constructor) 안에서의 this = 해당 생성자함수를 통해 만들어질 오브젝트
4. 이벤트리스너 안에서의 this = e.currentTarget 과 같음
+ 콜백함수안에서의 this 는 일반 함수와 같음 = window
+ 위에 콜백함수 안에서의 this 를 바꾸고 싶다면 arrow function 활용
사실 this 는 외워도 종종 까먹는다. 그럴 땐 걍 출력해보면 됨
'JavaScript' 카테고리의 다른 글
[JavaScript/ES6] var, let, const / hoising, 전역변수, 참조 (0) | 2024.08.26 |
---|---|
[JavaScript/ES6] Arrow function (0) | 2024.08.26 |
[JavaScript] 데이터타입 - null, 심벌, 객체 (0) | 2023.11.04 |
[JavaScript] 데이터 타입 - 템플릿 리터럴, 불리언 타입, undefined 타입 (0) | 2023.11.03 |
[JavaScript] 데이터 타입 - 숫자 타입, 문자열 타입 (0) | 2023.11.02 |