์๋ฐ์คํฌ๋ฆฝํธ this์ ๋ํด ์ ๋ฆฌํฉ๋๋ค.
this ์ ์
- ์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๋ ์๊ธฐ ์ฐธ์กฐ ๋ณ์๋ค.
- this๋ฅผ ํตํด ์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค์ ํ๋กํผํฐ๋ ๋ฉ์๋ค๋ฅผ ์ฐธ์กฐํ ์ ์๋ค.
this ์ฌ์ฉ
์๋ฐ์คํฌ๋ฆฝํธ์์ this ๋ฐ์ธ๋ฉ์ ํจ์ ํธ์ถ ๋ฐฉ์์ ์ํด ๋์ ์ผ๋ก ๊ฒฐ์ ๋๋ค.
- ์ ์ญ์์ this
this๋ ์ด๋์๋ ์ฐธ์กฐ ๊ฐ๋ฅํ๋ค.
๊ทธ๋ฆฌ๊ณ ์ ์ญ์์์ this๋ ์ ์ญ ๊ฐ์ฒด window๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
console.log(this) // window
- ์ผ๋ฐ ํจ์์์ this
์ผ๋ฐ ํจ์์์ this๋ฅผ ์ฌ์ฉ ์ ์ ์ญ ๊ฐ์ฒด window๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
ํ์ง๋ง strict mode์ผ ๊ฒฝ์ฐ undefined๊ฐ ๋ฐ์ธ๋ฉ๋๋ค.
๋ฉ์๋ ๋ด๋ถ์์ ์ผ๋ฐํจ์๋ก ํธ์ถ๋๋ฉด this๋ ์ ์ญ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
ES6๋ถํฐ ๊ฐ์ฒด ์์ ํจ์ ํ๋กํผํฐ ์ถ์ฝํ์ ๋ฉ์๋์ด๋ค. ์ด์ธ์๋ ์ผ๋ฐ ํจ์์ด๋ค.
function fn(){
console.log(this) // window
}
function fn2(){
'use strict'
console.log(this) // undefined
}
const obj = {
foo(){
function bar() {
console.log(this) // window
}
}
}
- ๋ฉ์๋์์ this
๋ฉ์๋ ๋ด๋ถ์์ this๋ฅผ ํธ์ถํ๋ฉด ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
์ผ๋ฐ ํจ์๋ก ํธ์ถ๋ ๋ชจ๋ ํจ์(์ค์ฒฉ ํจ์, ์ฝ๋ฐฑ ํจ์) ๋ด๋ถ์ this๋ ์ ์ญ ๊ฐ์ฒด๊ฐ ๋ฐ์ธ๋ฉ๋๋ค.
var x = 'global' // window.x = 'global'
const obj = {
x: 'local',
foo(){
console.log(this) // {x: 'local', foo: f}
console.log(this.x) // 100
// ๋ฉ์๋ ๋ด์์ ์ ์ํ ์ค์ฒฉ ์ผ๋ฐํจ์
function bar(){
console.log(this) // window
console.log(this.x) // 'global'
}
bar()
// ์ฝ๋ฐฑ ํจ์๊ฐ ์ผ๋ฐ ํจ์๋ก ํธ์ถ๋๊ธฐ ๋๋ฌธ์ this๋ window๋ฅผ ๊ฐ๋ฅดํจ๋ค.
setTimeout(function(){
console.log(this) // window
console.log(this.x) // 'global'
}, 100)
},
}
obj.foo()
์์ setTimeout์ ์ฝ๋ฐฑํจ์ ๋ด๋ถ์์ this๊ฐ ์ ์ญ๊ฐ์ฒด๊ฐ ์๋ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋ ค๋ฉด ํ์ดํ ํจ์ ๋๋ ๋ช ์์ ์ผ๋ก this ๊ฐ์ฒด ์ ๋ฌ(bind) ํด์ฃผ๋ฉด ๋๋ค.
var x = 'global' // window.x = 'global'
const obj = {
x: 'local',
foo(){
// ์ฝ๋ฐฑํจ์ ํ์ดํ ํจ์๋ก ํธ์ถ
setTimeout(()=>{
console.log(this.x) // 'local'
}, 1000)
// ๋ช
์์ ์ผ๋ก this ๊ฐ์ฒด ์ ๋ฌ
setTimeout(function(){
console.log(this.x) // 'local'
}.bind(this),1000)
},
}
obj.foo()
์์ฑ์ ํจ์ this ํธ์ถ
- ์์ฑ์ ํจ์๊ฐ ์์ฑํ ์ธ์คํด์ค๊ฐ ๋ฐ์ธ๋ฉ๋๋ค.
function Circle(radius){
this.radius = radius
this.getDiameter = function () {
return 2 * this.radius
}
}
const circle1 = new Circle(5)
console.log(circle1.getDiameter()) // 10
'๐ Study Note > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive - Ajax (0) | 2022.12.31 |
---|---|
๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive - ๋น๋๊ธฐ ํ๋ก๊ทธ๋๋ฐ (0) | 2022.12.31 |
๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive - ๊ฐ์ฒด ๋ฆฌํฐ๋ด (1) | 2022.12.25 |
๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive - ์คํ ์ปจํ ์คํธ (0) | 2022.12.11 |
๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive - ํธ์ด์คํ , var, let, const (0) | 2022.12.09 |