자바스크립트에서 this의 뜻은 사용하는 위치(스코프)에 따라 다음의 4개의 뜻을 갖는다.
1. 그냥 쓴 경우 or 일반 함수 안에서 그냥 쓴 경우 => window 객체
* 참고로 'use strict'를 써서 엄격 모드이면서, 일반 함수 안에서 쓰면 undefined가 된다.
console.log(this); // 그냥 쓴 경우: { window } (엄격 모드면 undefined)
[1,2,3,4].forEach(function (element) {
console.log(this); // 일반 함수 내에서 쓴 경우: { window } (엄격 모드면 undefined)
});
2. 객체의 메소드 안에서 쓴 경우 => 메소드의 주인인 객체
var object = {
printThis() {
console.log(this); // this: printThis()를 갖는 객체 object
}
innerObject: {
printThisToo() {
console.log(this); // this: printThisToo()를 갖는 객체 innerObject
},
},
};
만약 함수가 화살표함수이면, this는 상위 요소의 this를 물려받게 된다(화살표함수는 this를 재설정하지 않으므로).
var object = {
arrow: () => {
console.log(this); // arrow func은 this를 재설정하지 않음
};
}
object.arrow(); // {window} 출력
콜백 함수를 쓰는 경우
var object = {
array: [1, 2, 3, 4],
whatAboutCallback() {
object.array.forEach(function() {
console.log(this);
});
}
};
object.whatAboutCallback(); // {window} 출력
여기서 this는 forEach 안의 콜백함수에서 불렸으므로(일반 함수), window 객체를 뜻한다.
* 객체 내 메소드에서 this가 갖는 값을 이해했다면, 1번 즉 window 객체를 가리키게 되는 이유도 이해할 수 있다. window는 전역 객체로, js의 기본 함수들, 전역으로 선언된 변수 및 함수들을 담고 있다. 따라서 this가 1번과 같이 그냥 쓰이거나 일반 함수 내에서 쓰인 경우, this는 자신을 담고 있는 window라는 객체를 가리킨다.
3. 생성자(Constructor) 안에서 쓴 경우 => 인스턴스(instance)
인스턴스 = 생성자를 이용해 만든 객체
function constructObject() {
this.name = 'Kim';
}
var instance = new constructObject(); // this: instance
var anotherInstance = new constructObject(); // this: anotherInstance
4. eventListener 안에서 쓴 경우 => event.currentTarget
event.currentTarget은 이벤트가 발생한 요소를 가리킨다.
<button id = "버튼"> 버튼 </button>
<script>
document.getElementById('버튼').addEventListener('click', function(event) {
console.log(this); // this: e.currentTarget
console.log(event.currentTarget); // e.currentTarget: 이벤트가 발생한 요소(button)
});
});
</script>

'Frontend > JS, TS' 카테고리의 다른 글
| [웹브라우저 동작 원리] Stack, Queue (feat. Ajax 요청, SetTimeout, 이벤트리스너) (0) | 2023.01.28 |
|---|---|
| [상속] ES5: Object.create() / ES6: Class, extends, super() (0) | 2022.11.08 |
| [바닐라JS로 TODOLIST 만들기] 04 CHECK FINISHED LIST (0) | 2021.08.07 |
| [바닐라JS로 TODOLIST 만들기] 03 DELETE & CLEAR LIST (0) | 2021.08.06 |
| [바닐라JS로 TODOLIST 만들기] 02 SET PRIORITY (StarRating) (0) | 2021.08.06 |