👨🎓 JS에서 종종 사용하는 this는 최소 3가지이상의 뜻을 가지는데 이번에 정리할려고함.
1-1. 그냥 쓰거나 일반 function함수에서 쓰게되면 window를 뜻함.
그냥 HTML 파일 아무거나 하나 만들고 스크립트 태그에
console.log(this)
이렇게 쳐보면 window 객체가 뜸.
일반 함수 내에서 this라는 값을 불러보면
function logic(){
console.log(this)
}
logic();
똑같이 this라는 값은 window 라고 출력됨.
단, script가 'use strict' 모드 일땐 undefined로 출력됨.
window는 모든 전역변수, 함수, DOM을 보관하고 관리하는 전역객체임
document.getElementById(),
alert(), console.log(),
var a = 0 , var b = 0
대충 쉽게 말하면 이런애들이 만들어져 있거나 변수를 선언해서 만들게되면 여기 저장됨
2. 오브젝트에서의 this
var obj = {
data : 'Kim',
func : function(){ console.log(this) }
}
obj.func();
실행해보면 콘솔에 obj가 찍히게 되는데, 오브젝트에서의 this는 실행구문을 감싸는 부모를 지칭함.
3. eventlistener 안에서 쓰면 this는 e.currentTarget을 가르킴.
document.getElementById('button').addEventListener('click', function(e){
console.log(this)
});
· 헷갈릴 수 있는 부분
document.getElementById("button").addEventListener("click", function (e) {
var array = [1, 2, 3];
array.forEach(function (item, index) {
console.log(this);
});
});
위 함수를 실행하면 e.currentTarget나 item이 찍힐 것 같지만 window나 undefined가 뜨게됨.
item이 뜨기위해서는 콘솔에 item을 찍었어야 됐고
e.currentTarget는 forEach 일반함수 안에서 사용 했기 때문에 this로 처리되지 않게된다.
e.currentTarget을 처리하고 싶다면 일반함수 >> arrow function으로 대체하면 가능하다.