[JavaScript] ํ์ดํ ํจ์์ ์ผ๋ฐ ํจ์์ ์ฐจ์ด
์๋ฐ์คํฌ๋ฆฝํธ์์ ์ผ๋ฐ ํจ์๋ ํจ์๋ฅผ ์ ์ธํ ๋ this์ ๋ฐ์ธ๋ฉํ ๊ฐ์ฒด๊ฐ ๋์ ์ผ๋ก ๊ฒฐ์ ๋๋ค.
์๋ ํจ์๊ฐ ์ด๋ป๊ฒ ์คํ๋ ์ง ์์ํด๋ณด์.
const obj = {
name: 'minho',
intro: function() {
console.log(this.name)
setTimeout(function() {
console.log(this.name)
}, 1000)
}
}
obj.intro()
๋
ผ๋ฆฌ์ ์ผ๋ก ์๊ฐํด๋ณด๋ฉด ๋น์ฐํ minho๊ฐ ๋ ๋ฒ ๋ฐ๊ฑฐ๋ผ ์๊ฐํ๋ค.
๊ทธ๋ฌ๋ ๋ ๋ฒ์งธ console.log๋ undefined๊ฐ ๋จ๋ ๊ฑธ ํ์ธํ ์ ์๋ค. ์ด์ ๋ ๋ฌด์์ผ๊น?
setTimeout ๋ด๋ถ์ this๋ window๋ฅผ ๊ฐ๋ฅดํค๊ธฐ ๋๋ฌธ์ด๋ค.
ํด๋น ๋ฌธ์ ๋ฅผ ์๋ ์ฝ๋์ ๊ฐ์ด bind, call, apply๋ฅผ ํตํด ์ด๋์ ๋ฐ์ธ๋ฉํ ์ง ์ ํด์ค ์ ์์ง๋ง ๋ ํธ๋ฆฌํ ๋ฐฉ๋ฒ์ด ์๋ค.
const obj = {
name: 'minho',
intro: function() {
console.log(this.name)
setTimeout(function() {
console.log(this.name)
}.bind(this), 1000)
}
}
obj.intro()
ํ์ดํ ํจ์
const obj = {
name: 'minho',
intro: function() {
console.log(this.name)
setTimeout(() => {
console.log(this.name)
}, 1000)
}
}
obj.intro()
์์๊ณผ ๊ฐ์ด minho๊ฐ ๋ ๋ฒ ๋จ๋ ๊ฑธ ํ์ธํ ์ ์๋ค.
ํ์ดํ ํจ์๋ ์ผ๋ฐ ํจ์์ ๋ฌ๋ฆฌ ์ธ์ ๋ ์์ ์ค์ฝํ์ this๋ฅผ ๊ฐ๋ฅดํค๊ธฐ ๋๋ฌธ์ ์๊ฐํ์ง ๋ชปํ ์ค๋ฅ๋ฅผ ๋ฐฉ์งํ ์ ์๋ค.
๊ทธ๋ฌ๋ ํ์ดํ ํจ์๋ฅผ ์ฌ์ฉํ๋ฉด ์๋๋ ๊ฒฝ์ฐ๊ฐ ์๋ค.
๋ฉ์๋๋ฅผ ์ ์ํ ๋
const obj = {
name: 'minho',
intro: () => console.log(`Hi my name is ${this.name}`)
};
obj.intro();
์ค์ ํธ์ถ์ ํ์ธํด๋ณด๋ฉด 'Hi my name is undefined` ๊ฐ ๋จ๋ ๊ฑธ ํ์ธํ ์ ์๋ค.
๋น์ฐํ๋ค. ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฅดํค๋ ๊ฒ ์๋๋ผ ์ ๊ธฐ์์ this๋ ์์ ์ปจํ์คํธ์ธ ์ ์ญ ๊ฐ์ฒด์ผ ์ ๋ฐ์ ์๋ค.
const obj = {
name: 'minho',
intro() {
console.log(`Hi my name is ${this.name}`)
}
};
obj.intro();
๋ฉ์๋๋ ์ ์ํ ๋๋ ์ถ์ฝ ๋ฉ์๋ ํํ์ ์ฌ์ฉํ์.
๋ฌธ์ ์ ๋ค์ ์ฃผ์ํ๋ฉฐ ํ์ดํํจ์๋ฅผ ์ฌ์ฉํ์!