๐ฏJavaScript์์ Arrow Functions vs. Regular Functions
Source: Dev.to

JavaScript ๋ฉด์ ์์ ๊ฐ์ฅ ํํ ํผ๋๋๋ ๋ถ๋ถ ์ค ํ๋๋ ํ์ดํ ํจ์์ ์ผ๋ฐ ํจ์์์ this๊ฐ ๋ค๋ฅด๊ฒ ๋์ํ๋ค๋ ์ ์
๋๋ค. this๊ฐ ๋๋๋ก undefined๊ฐ ๋์ค๋ ์ด์ ๊ฐ ๊ถ๊ธํ๋ค๋ฉด, ์ด ๊ฐ์ด๋๋ฅผ ํตํด ๋ช
ํํ ์ดํดํ ์ ์์ต๋๋ค.
1๏ธโฃ ์ผ๋ฐ ํจ์ โ this๋ ๋์
์ผ๋ฐ ํจ์์์๋ this์ ๊ฐ์ด ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋๋์ง์ ๋ฐ๋ผ ๊ฒฐ์ ๋๋ฉฐ, ์ ์๋ ์์น์๋ ๋ฌด๊ดํฉ๋๋ค.
const user = {
name: 'Richa',
greet: function () {
console.log(this.name);
}
};
user.greet(); // Richa
const greetCopy = user.greet;
greetCopy(); // โ undefined (or window.name in browsers)
์ ์ด๋ฐ ์ผ์ด ๋ฐ์ํ ๊น
this๋ ํธ์ถ ์ปจํ
์คํธ์ ์ํด ๊ฒฐ์ ๋ฉ๋๋ค. ํจ์๊ฐ ๊ฐ์ฒด ์ฐธ์กฐ๋ฅผ ์์ผ๋ฉด this๋ ๋ ์ด์ user๋ฅผ ๊ฐ๋ฆฌํค์ง ์๊ฒ ๋ฉ๋๋ค.
2๏ธโฃ ํ์ดํ ํจ์ โ this๋ ๋ ์์ปฌ
ํ์ดํ ํจ์๋ ์์ ๋ง์ this๋ฅผ ๊ฐ์ง ์์ต๋๋ค. ๋์ ์์ ์ค์ฝํ์์ this๋ฅผ ์์ํฉ๋๋ค.
const user = {
name: 'Richa',
greet: () => {
console.log(this.name);
}
};
user.greet(); // โ undefined
์ ๊ทธ๋ฐ๊ฐ?
ํ์ดํ ํจ์๊ฐ ์ ์ญ ์ค์ฝํ์์ ์์ฑ๋์๊ธฐ ๋๋ฌธ์, ์ ์ญ this๋ฅผ ์์๋ฐ์ผ๋ฉฐ user ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค์ง ์์ต๋๋ค.
โ ์ฌ๋ฐ๋ฅธ ์ ๊ทผ๋ฒ
๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋ this๊ฐ ํ์ํ ๋๋ ์ผ๋ฐ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ธ์.
const user = {
name: 'Richa',
greet() {
console.log(this.name);
}
};
user.greet(); // โ
Richa
3๏ธโฃ ์ต์ ํ์ฉ ์ฌ๋ก: ์ผ๋ฐ ํจ์ ๋ด๋ถ์์ ํ์ดํ ํจ์ ์ฌ์ฉ
ํ์ดํ ํจ์๋ ๋ฉ์๋๋ ์ฝ๋ฐฑ ๋ด๋ถ์์ ์ฌ์ฉํ ๋ ๋น์ ๋ฐํฉ๋๋ค. ๊ฐ์ this ์ปจํ
์คํธ๋ฅผ ์ ์งํ๊ธฐ ๋๋ฌธ์
๋๋ค.
const team = {
name: 'Frontend',
members: ['Richa', 'Jane'],
showMembers() {
this.members.forEach(member => {
console.log(`${member} is part of ${this.name}`);
});
}
};
team.showMembers();
// Richa is part of Frontend
// Jane is part of Frontend
forEach ์์ ์ผ๋ฐ ํจ์๋ฅผ ์ฌ์ฉํ๋ค๋ฉด this.name์ undefined๊ฐ ๋์์ ๊ฒ์
๋๋ค.
๋ฉด์ ๋๋น ๋ต๋ณ
- ์ผ๋ฐ ํจ์๋ ๋์
this๋ฅผ ๊ฐ์ง๋๋ค โ ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋๋ค. - ํ์ดํ ํจ์๋ ๋ ์์ปฌ
this๋ฅผ ๊ฐ์ง๋๋ค โ ์์ ์ค์ฝํ์์ ์์๋ฐ์ต๋๋ค.
๐ฏ ์ถ๊ฐ ํ
React ์ปดํฌ๋ํธ์์ this๋ฅผ ์ผ๊ด๋๊ฒ ์ ์งํ๊ณ ์ถ์ ๋ ํ์ดํ ํจ์๋ฅผ ์์ฃผ ์ฌ์ฉํ๋ ์ด์ ๊ฐ ๋ฐ๋ก ์ด๊ฒ์
๋๋ค.
ํต์ฌ ์ ๋ฆฌ
ํ์ดํ ํจ์๋ ๋จ์ํ ์ฝ๋๋ฅผ ์งง๊ฒ ์ฐ๋ ๋ฐฉ๋ฒ์ด ์๋๋ผ ์ปจํ ์คํธ๋ฅผ ๋ณด์กดํด ์ค๋๋ค.
| ํน์ง | ์ผ๋ฐ ํจ์ | ํ์ดํ ํจ์ |
|---|---|---|
์์ฒด this ๋ณด์ ์ฌ๋ถ | โ Yes | โ No |
this๊ฐ ํธ์ถ ์์น์ ์์กด | โ Yes | โ No |
| ๊ฐ์ฒด ๋ฉ์๋์ ์ ํฉ | โ Yes | โ No |
| ์ฝ๋ฐฑ์ ์ ํฉ | โ Often No | โ Yes |
์ต์ข ์๊ฐ
๋์ this์ ๋ ์์ปฌ this์ ์ฐจ์ด๋ฅผ ์ดํดํ๋ฉด ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ด ๋ฉ๋๋ค:
- ๋ ๊น๋ํ๊ฒ โ
- ์ดํดํ๊ธฐ ์ฌ์ โ
- ๋ฒ๊ทธ๊ฐ ์ ๊ฒ โ
ํ์ดํ ํจ์๋ ๋จ์ํ ๋ฌธ๋ฒ์ ์ ์ฝํ๋ ๊ฒ์ด ์๋๋ผ ์ปจํ ์คํธ๋ฅผ ์ ์ฝํฉ๋๋ค. โก