Front/JS & jQuery

[js] ํ™”์‚ดํ‘œ ํ•จ์ˆ˜(=>)๋Š” this๋ฅผ ๋ฐ”์ธ๋”ฉํ•˜์ง€ ์•Š๋Š”๋‹ค

์˜ค์„ ์ง€โ™ฌ 2025. 2. 12. 19:22
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
๋ฐ˜์‘ํ˜•