기본적으로 this는 window객체
console.log(this) // window
case1
const obj = {
name : 'yoo',
sayName:function(){
console.log(this.name) // 지금 this는 호출안해서 뭔지 모름
}
}
obj.sayName()
// 출력결과 'yoo', this 는 함수를 호출할때 결정되고 obj객체를 가리킴
case2
const obj = {
name : 'yoo',
sayName : function(){
console.log(this.name)
function inner(){
console.log(this.name)
}
inner() //inner앞에 아무것도 없다 이때 inner을 호출한것은 window
//앞에 아무것도 없으면 window가 호출한 것!*
}
}
obj.sayName() // 출력결과 'yoo', 그리고 빈 문자열(window.name=''니까)*
// 첫번째 this는 obj, 두번째 this는 window*
case3
const obj = {
name : 'yoo',
sayName:function(){
console.log(this.name)
const inner = ()=> {
console.log(this.name)
}
inner() }
}
obj.sayName() // 무엇이 출력될까? 1. 'yoo' 2. 'yoo'
//화살표 함수를 쓰면 화살표함수의 this는 자신을 선언한 함수의 this를 계승받는다.
// 즉, sayName 함수의 this를 계승받는데 지금 sayName을 obj가 호출하므로 sayName의 this는
// obj이고 화살표함수 inner의 this도 obj가된다.
case4 this가 애매한경우
const headerBtn = document.querySelector('#headerBtn')
header.addEventListener('click', ()=>{
console.log(this)
})
//여기서 this가 window가아니고 header인 이유가 뭘까? 보통 이런걸 우리는 경험으로 알고 외웠다.
//일단 이유는 알수없다. 내부를 뜯어봐야한다. 참고로 내부는 c++로 되어있다.
//그렇다면 추론을 해보자
function addEventListener(str,callback){
callback() //내부가 이렇게 되어있다면 this는 window일것이다.
callback.call(header) // 이렇게 되어있지 않을까?
//아니면 지금 addEventListener은 header이 호출했으므로 this가 header이니까
callback.call(this) //이런식으로 되어있을수도있다.
출처