실행 컨텍스트(global, function 또는 eval)의 프로퍼티는 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값이든 될 수 있습니다.
일반함수와 화살표함수의 this 차이
일반함수에서 this
const gaeng = {
name: 'Gaeng',
nomer: function () {
console.log(this.name)
},
arrow: () => {
console.log(this.name)
}
}
gaeng.nomer()
gaeng.arrow()
const amy = {
name: 'Amy',
nomer: gaeng.nomer,
arrow: gaeng.arrow
}
amy.nomer()
amy.arrow()
heropy.nomer()
를 호출했을 때 nomer
에서 this
는 gaeng
이다.
console.log(this.name)
= gaeng
의 name
부분을 꺼내서 사용하라는 말이기 때문에 console창에 Gaeng이 출력되는 것이다.
amy.nomer()
를 호출했을 때 nomer
에서 this
는 amy
이다.
nomer
에 gaeng.nomer
= function () {console.log(this.name)}
이 부분을 가져오라는 뜻 이기때문에 console.log(this.name)
= amy
의 name
부분을 꺼내서 사용하라는 말이다. 그러므로 console창에 Amy가 출력되는 것이다.
화살표함수에서 this
const timer = {
name: 'Gaeng',
timeout: function () {
setTimeout(() => {
console.log(this.name)
}, 2000)
}
}
timer.timeout()
timer.timeout()
를 호출했을 때 timeout
안에 함수 범위에서 this
가 정의되는 것이고 그 함수 부분에서 this
는 곧 일반함수가 정의된 timer
라는 객체데이터를 가르키기 때문에 여기서 this
= timer
가 되는 것입니다.
console.log(this.name)
= timer
의 name
부분을 꺼내서 사용하라는 말이다. 그러므로 console창에 Gaeng가 출력되는 것이다.