๐ setTimeout๊ณผ ๊ฐ์ ๋น๋๊ธฐ ์ฝ๋์์ ํ์ดํ ํจ์๊ฐ ์ธ๋ถ this๋ฅผ ์ ์งํ๋ค๋ ์๋ฏธ
โก ํ์ดํ ํจ์(=>)๋ this๋ฅผ ๋ฐ์ธ๋ฉํ์ง ์๊ณ , ์ ์ธ๋ ์์น์ this๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ค.
โก ์ผ๋ฐ ํจ์(function() {})๋ ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ this๊ฐ ๋ฌ๋ผ์ง๋ค.
์ด ์ฐจ์ด๊ฐ setTimeout, setInterval ๊ฐ์ ๋น๋๊ธฐ ์ฝ๋์์ this๋ฅผ ์ ์งํ๋๋ฐ ์ํฅ์ ์ค๋ค๋ ์๋ฏธ๋ค.
โ 1. setTimeout์์ ์ผ๋ฐ ํจ์(function) ์ฌ์ฉ
function Timer() {
this.seconds = 0;
setInterval(function() {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
const myTimer = new Timer();
๐น ์ค๋ฅ ๋ฐ์! (this.seconds๊ฐ undefined)
๐น ์? setInterval ๋ด๋ถ์ this๋ Timer ๊ฐ์ฒด๊ฐ ์๋๋ผ window(๋ธ๋ผ์ฐ์ ) ๋๋ global(Node.js)๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
โ ๋ฌธ์ ์์ธ:
- ์ผ๋ฐ ํจ์(function)์์ this๋ ํธ์ถ๋ ๋ฐฉ์์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๊ฒฐ์ ๋จ.
- setInterval์ ์ฝ๋ฐฑ ํจ์๋ ์ผ๋ฐ ํจ์์ฒ๋ผ ํธ์ถ๋๋ฏ๋ก this๊ฐ ์ ์ญ ๊ฐ์ฒด(window/global)๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
โ 2. setTimeout์์ ํ์ดํ ํจ์(=>) ์ฌ์ฉ
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
const myTimer = new Timer();
๐น ์ ์ ๋์! (this.seconds๊ฐ 1์ด๋ง๋ค ์ฆ๊ฐ)
๐น ์? ํ์ดํ ํจ์(=>)๋ ์์ ์ด ์ ์ธ๋ ์์น์ this๋ฅผ ์ ์งํ๊ธฐ ๋๋ฌธ.
โ ํด๊ฒฐ ๋ฐฉ๋ฒ:
- ํ์ดํ ํจ์๋ ์ค์ค๋ก this๋ฅผ ๋ง๋ค์ง ์๊ณ , ๋ฐ๊นฅ์ this๋ฅผ ์ ์งํ๋ค.
- ์ฆ, Timer ๊ฐ์ฒด์ this๋ฅผ ๊ทธ๋๋ก ๊ฐ์ ธ์ค๊ธฐ ๋๋ฌธ์ this.seconds++๊ฐ ์ ์์ ์ผ๋ก ๋์ํ๋ค.
โ 3. ์์ : ์ผ๋ฐ ํจ์ vs ํ์ดํ ํจ์ this ๋น๊ต
const obj = {
name: "Alice",
normalFunction: function() {
setTimeout(function() {
console.log(this.name);
}, 1000);
},
arrowFunction: function() {
setTimeout(() => {
console.log(this.name);
}, 1000);
}
};
obj.normalFunction(); // ์ถ๋ ฅ: undefined (window.name)
obj.arrowFunction(); // ์ถ๋ ฅ: Alice (obj.name)
๐น normalFunction()์์๋ setTimeout ๋ด๋ถ์ ์ผ๋ฐ ํจ์๊ฐ this๋ฅผ window๋ก ๋ณ๊ฒฝํด๋ฒ๋ฆผ → undefined
๐น arrowFunction()์์๋ ํ์ดํ ํจ์๊ฐ this๋ฅผ ์ ์งํ๋ฏ๋ก obj.name์ด ์ ์ ์ถ๋ ฅ
๐ ์ ๋ฆฌ
โ
์ผ๋ฐ ํจ์(function)๋ this๊ฐ ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ ๋ฐ๋ → setTimeout ์์์๋ window(์ ์ญ ๊ฐ์ฒด)๋ก ๋ฐ๋์ด ๋ฒ๋ฆผ.
โ
ํ์ดํ ํจ์(=>)๋ this๋ฅผ ๋ฐ๊พธ์ง ์๊ณ , ์ ์ธ๋ ์์น์ this๋ฅผ ์ ์ง → setTimeout ์์์๋ this๊ฐ ์ ์ง๋จ.
โ
๋ฐ๋ผ์ ๋น๋๊ธฐ ์ฝ๋(setTimeout, setInterval)์์ this๋ฅผ ์ ์งํ๊ณ ์ถ๋ค๋ฉด ํ์ดํ ํจ์๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค. ๐
'Front > JS & jQuery' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[js][datatables] responsive: { details: false } (0) | 2025.02.21 |
---|---|
[js][datatables] fnRecordsDisplay() (0) | 2025.02.20 |
[js] ํ์ดํ ํจ์(=>)๋ this๋ฅผ ๋ฐ์ธ๋ฉํ์ง ์๋๋ค (0) | 2025.02.12 |
ํฌ๋กค๋ง (0) | 2025.02.03 |
[js][Echarts] x์ถ ๋ผ๋ฒจ ์์น ์กฐ์ / margin (0) | 2025.01.30 |