this
์ผ๋ฐ(Normal) ํจ์๋ ํธ์ถ ์์น์์ ๋ฐ๋ผ this ์ ์!
ํ์ดํ(Arrow) ํจ์๋ ์์ ์ด ์ ์ธ๋ ํจ์ ๋ฒ์์์ this ์ ์!
const imae = {
name: 'Imae',
normal: function () {
console.log(this.name)
},
arrow: () => {
console.log(this.name)
}
}
imae.normal()
imae.arrow()
์คํ ๊ฒฐ๊ณผ
Imae
undefined
๋ ๋ค๋ฅธ ์์น์์ amy๋ผ๋ ๋ณ์๋ฅผ ๋ง๋ค์ด๋ด์ ๊ฐ์ฒด ๋ฐ์ดํฐ๋ฅผ ํ ๋นํ๋ค.
imae.normal, imae.arrow ๋ฑ ์์ ์๋ ๋ฐ์ดํฐ๋ฅผ amy์ ํ ๋น๋๋ ๊ตฌ์กฐ์ด๋ค.
const amy = {
name: 'Amy',
normal: imae.normal,
arrow: imae.arrow
}
amy.normal()
amy.normal()
์คํ ๊ฒฐ๊ณผ
Amy
undefined
์ผ๋ฐ ํจ์๋ก ๋ง๋ ๋ถ๋ถ์ this์ name์ amy๋ก ์ ์คํํ์๊ณ , ํ์ดํ ํจ์๋ก ๋ง๋ ๋ถ๋ถ์ ์ ์ธ๋ ๊ทธ this์ ์์น์์ ์คํ๋๊ธฐ ๋๋ฌธ์ undefined๊ฐ ์คํ๋๋ค.
function User(name) {
this.name = name
}
User.prototype.normal = function () {
console.log(this.name)
}
User.prototype.arrow = () => {
console.log(this.name)
}
const imae = new User('Imae')
imae.normal()
imae.arrow()
์คํ ๊ฒฐ๊ณผ
Imae
undefined
์ด๋ฒ์๋ ์ ๋ฒ ์๊ฐ์ ๋ฐฐ์ด ์์ฑ์ ํจ์๋ฅผ ํตํด์ name์ ์ถ๋ ฅํ๋ ์์ ๋ฅผ ๋ง๋ค์๋ค.
๋งค๊ฐ๋ณ์ name์ ๋ฐ์์ prototype์ ์ด์ฉํด์ ์ผ๋ฐํจ์, ํ์ดํํจ์๋ฅผ ๋ฐ์์ ์ฝ์์ ์ถ๋ ฅํ๋ค.
imae๋ผ๋ ๋ณ์๋ฅผ new๋ผ๋ ํค์๋๋ก ์์ฑ์ํจ์๋ฅผ ์คํํ๋ฉด ๊ฐ์ฒด๋ฐ์ดํฐ์ด๊ณ , normal(), arrow()๋ฅผ ์คํํ ์ ์๋ค.
ํ์ดํํจ์๋ ํจ์ ๋ฒ์์์ ์์ ์ด ์ ์ธ๋ ํจ์ ๋ฒ์์์ this๋ฅผ ์ ์ํ๊ธฐ ๋๋ฌธ์ ์ด๋ฒ์๋ undefined๋ผ๋ ๊ฒฐ๊ณผ๊ฐ ์ถ๋ ฅ๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
const timer = {
name: 'imae',
timeout: function () {
serTimeout(function () {
console.log(this.name)
}, 2000)
}
}
timer.timeout()
์คํ ๊ฒฐ๊ณผ
undefined
2์ด ๋ค์ ์คํ ๊ฒฐ๊ณผ undefined๊ฐ ๋์ฌ ๊ฒ์ด๋ค. ํ์ด๋จธ ํจ์๋ฅผ ์ฝ๋ฐฑํ๋๋ฐ ์ผ๋ฐ ํจ์๋ฅผ ์ฐ๋ฉด ์๋๋ค.
ํจ์ ๋ด๋ถ์ ์ถ๋ ฅ ๋ด์ฉ์ด ์์ผ๋ฉด ํ์ดํ ํจ์๋ฅผ ์จ์ผ ํ๋ค.
const timer = {
name: 'imae',
timeout: function () {
setTimeout(() => {
console.log(this.name)
}, 2000)
}
}
timer.timeout()
์คํ ๊ฒฐ๊ณผ
imae
ํ์ดํ ํจ์๋ฅผ ์ฐ๋ฉด ์คํ๊ฒฐ๊ณผ๊ฐ ์ ์ถ๋ ฅ๋๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
ํจ์ ๋ฒ์์์ this๊ฐ ์ ์๋๊ธฐ ๋๋ฌธ์ imae๋ผ๋ name์ด ์ ์ถ๋ ฅ๋๋ ๊ฒ์ด๋ค.
'๐ค Language > ๐จ JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
JS. ์์(ํ์ฅ) (0) | 2022.02.15 |
---|---|
JS. ES6 Classes (0) | 2022.02.15 |
JS. ์์ฑ์ ํจ์(prototype) (0) | 2022.02.15 |
JS. ์ฝ๋ฐฑ(CallBack) (0) | 2022.02.13 |
JS. ํ์ด๋จธ ํจ์ (0) | 2022.02.13 |