this
이게 이게 뭐예요?
JavaScript this
객체를 가리키는 키워드. 호출한 애==this
this = 호출한 객체. 호출한 게 없으면 window 있으면 this를 호출한 객체.
function printThis(){ console.log(this)}
printThis() // this === 윈도우 객체
let person1 = {
name:'안녕',
printThis:printThis,
}
person1.printThis() // this === person1
//!!주의!!
//callback등 특이상황에선 예상한대로 안나오고
//다르게 나올 수 있으니 bind를 시켜주면
//원하는대로 나옴.
let person = {
console.log(this) //person
hello:function(){setTimeout(function(){
console.log(this); //window가 나옴.
})}}
person.hello() //window가 this가 됨.
let btn = document.qeurySelector('button');
btn.addEventListener('click',function() {
console.log(this) // btn이 나옴.
})
this를 따로 할당할 수도 있음. 다만 딱 한번만 등록 가능.
let person1 = {~~}
function printThis(){
console.log(this);
}
let printThis1 = printThis.bind(person1)
//디폴트는 window
printThis1(); // person1
this 예외
- 전역 스코프에서 this =윈도우 객체
-
화살표 함수는 좀 달라짐
- 왜냐면 화살표 함수는 자신을 감싼(외부) 스코프에서 this를 물려받기 때문에 아까는 printThis가 window로 떳지만 저 setTimeout안에 콜백을 ()⇒로 바꾸면 person이 this가 됨.
- 다만 화살표 함수를 객체 메서드 선언할 때 사용하면 원하는대로 안됨…
왜냐? 함수 화살표가 선언될 당시의 상위 스코프(렉시컬 스코프)의 this를 물려받기에, 객체 메서드를 감싸는 외부 스코프는 전역이고, 그러기에 window객체가
jsx let person = { name: '코딩', printThis:()=>{ console.log(this) //window 객체 출 } }
- 또한 addEventListenr 함수의 콜백 함수에서 사용하면 this가 상위 컨텍스트를 가리킴.. 일반함수로 해야 호출한 요소가 됨. 즉 화살표 함수는 전역 스코프에서 선언된것과 유사하게 동작하기에 this === window임. 그러나 일반 함수의 this는 이벤트를 발생 시킨 DOM요소 (event target)을 가리키도록 바인딩 되기에 이벤트를 일으킨 button이 바뀌게 되는 것.
let btn = document.querySelector('button'); button.addEventListener('click',()=>{ console.log(this===window);//true }) let btn = document.querySelector('button'); button.addEventListener('click',function() { console.log(this===button);//true })
- strict Mode에서도 좀 달라짐.
- 호출한 애가 없으면 window가 아닌 undefined가 됨.