Front/JS & jQuery

[js] ๋น„๋™๊ธฐ ์ฝ”๋“œ์—์„œ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

์˜ค์„ ์ง€โ™ฌ 2025. 2. 13. 20:22
728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ 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๋ฅผ ์œ ์ง€ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค. ๐Ÿš€

728x90
๋ฐ˜์‘ํ˜•