728x90
๋ฐ์ํ
๐ ํ์ดํ ํจ์(=>)๋ this๋ฅผ ๋ฐ์ธ๋ฉํ์ง ์๋๋ค
ํ์ดํ ํจ์๋ ์ผ๋ฐ ํจ์(function)๊ณผ ๋ค๋ฅด๊ฒ this๋ฅผ ์์ฒด์ ์ผ๋ก ๋ฐ์ธ๋ฉํ์ง ์๋๋ค.
์ฆ, ํ์ดํ ํจ์ ๋ด๋ถ์์ this๋ฅผ ์ฌ์ฉํ๋ฉด, ์์ ์ด ์ํ ์ค์ฝํ์ this๋ฅผ ๊ทธ๋๋ก ๊ฐ์ ธ์จ๋ค(lexical this).
๐ 1. ์ผ๋ฐ ํจ์์ ํ์ดํ ํจ์์ this ์ฐจ์ด
โ (1) ์ผ๋ฐ ํจ์์์์ this
์ผ๋ฐ ํจ์(function)์์ this๋ ํจ์๋ฅผ ํธ์ถํ ๊ฐ์ฒด์ ๋ฐ๋ผ ๋ฌ๋ผ์ง.
const obj = {
value: 42,
normalFunction: function() {
console.log(this.value); // obj๋ฅผ ๊ฐ๋ฆฌํด (this === obj)
}
};
obj.normalFunction(); // ์ถ๋ ฅ: 42
์ผ๋ฐ ํจ์(function)๋ this๋ฅผ ํธ์ถํ ๊ฐ์ฒด(obj)์ ๋ฐ์ธ๋ฉํ๋ค.
โ (2) ํ์ดํ ํจ์์์์ this
ํ์ดํ ํจ์๋ ์๊ธฐ ์์ (ํจ์)์๊ฒ this๋ฅผ ๋ฐ์ธ๋ฉํ์ง ์๊ณ , ์์ ์ด ์ ์ธ๋ ์์น์ this๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ค.
const obj = {
value: 42,
arrowFunction: () => {
console.log(this.value); // this๋ obj๊ฐ ์๋๋ผ ์ธ๋ถ(์ ์ญ) ์ค์ฝํ๋ฅผ ๊ฐ๋ฆฌํด
}
};
obj.arrowFunction(); // ์ถ๋ ฅ: undefined (์ ์ญ ๊ฐ์ฒด์์ value๊ฐ ์๊ธฐ ๋๋ฌธ)
ํ์ดํ ํจ์์์๋ this๊ฐ obj๊ฐ ์๋๋ผ, obj๋ฅผ ๊ฐ์ธ๋ ์ธ๋ถ ์ค์ฝํ(์ ์ญ window ๋๋ global)๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
728x90
๋ฐ์ํ
'Front > JS & jQuery' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[js][datatables] fnRecordsDisplay() (0) | 2025.02.20 |
---|---|
[js] ๋น๋๊ธฐ ์ฝ๋์์ ํ์ดํ ํจ์ (0) | 2025.02.13 |
ํฌ๋กค๋ง (0) | 2025.02.03 |
[js][Echarts] x์ถ ๋ผ๋ฒจ ์์น ์กฐ์ / margin (0) | 2025.01.30 |
[js][Echarts] label ์์น ์ธ๋ถ ์์ / offset (0) | 2025.01.29 |