๋ฐ์ํ
this
this๋ ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋๋๋์ ๋ฐ๋ผ ๊ฐ์ด ๋ฌ๋ผ์ง๋ค.
์ผ๋ฐ ํจ์ โ ํธ์ถํ ์ฃผ์ฒด๊ฐ this
const user = {
name: "Alice",
greet() {
console.log(this.name);
}
};
user.greet(); // "Alice" โ user๊ฐ ํธ์ถํ์ผ๋ this = user
const greet = user.greet;
greet(); // undefined โ ๊ทธ๋ฅ ํธ์ถํ๋ฉด this = ์ ์ญ
ํ์ดํ ํจ์ โ this๊ฐ ์์, ๋ฐ๊นฅ ์ค์ฝํ ๊ทธ๋๋ก
const user = {
name: "Alice",
greet: () => {
console.log(this.name); // undefined
}
};
ํ์ดํ ํจ์๋ ์๊ธฐ๋ง์ this๊ฐ ์๋ค. ์ ์ธ๋ ์์น์ ๋ฐ๊นฅ this๋ฅผ ๊ทธ๋๋ก ์.
๊ฐ์ฒด ๋ฆฌํฐ๋ด({})์ ์ค์ฝํ๋ฅผ ๋ง๋ค์ง ์๊ธฐ ๋๋ฌธ์, ๋ฐ๊นฅ this๋ ์ ์ญ์ด ๋๋ค.
์ค๋ฌด์์ ์์ฃผ ๋์ค๋ ๋ฒ๊ทธ + ํด๊ฒฐ
// ๋ฒ๊ทธ: setTimeout ์ฝ๋ฐฑ์ this๋ ์ ์ญ
const user = {
name: "Alice",
greet() {
setTimeout(function() {
console.log(this.name); // undefined
}, 100);
}
};
// ํด๊ฒฐ: ํ์ดํ ํจ์๋ก ๋ฐ๊พธ๋ฉด ๋ฐ๊นฅ greet์ this๋ฅผ ๊ทธ๋๋ก ์
const user = {
name: "Alice",
greet() {
setTimeout(() => {
console.log(this.name); // "Alice"
}, 100);
}
};
์ค๋ฌด ๊ท์น
๊ฐ์ฒด ๋ฉ์๋ โ ์ผ๋ฐ ํจ์ (this๊ฐ ํ์ํ๋๊น)
์ฝ๋ฐฑ, ์ค์ฒฉ ํจ์ โ ํ์ดํ ํจ์ (๋ฐ๊นฅ this๋ฅผ ๊ทธ๋๋ก ์ฐ๋ ค๊ณ )๋ฉด์ ๋ต๋ณ
"
this๋ ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋๋๋์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋๋ค. ์ผ๋ฐ ํจ์๋ ํธ์ถํ ์ฃผ์ฒด๊ฐthis๊ฐ ๋๊ณ , ํ์ดํ ํจ์๋ ์๊ธฐ๋ง์this๊ฐ ์์ด์ ์ ์ธ๋ ์์น์ ๋ฐ๊นฅthis๋ฅผ ๊ทธ๋๋ก ์๋๋ค."
๋ฐ์ํ