Library/JQuery

๐Ÿ“š ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ this vs ์ œ์ด์ฟผ๋ฆฌ $(this) ์ฐจ์ด

์ธํŒŒ_ 2021. 9. 29. 13:49

js-jquery-this

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ this

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ this๋Š” ํ˜„์žฌ ์‹คํ–‰ ์ปจํ…์ŠคํŠธ์—์„œ ์ฐธ์กฐ๋˜๋Š” ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ ํ•จ์ˆ˜ ๋‚ด์—์„œ ์‚ฌ์šฉ๋˜๋ฉฐ, ํ•จ์ˆ˜ ํ˜ธ์ถœ ๋ฐฉ์‹์— ๋”ฐ๋ผ this๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฐ์ฒด๊ฐ€ ๋‹ฌ๋ผ์ง€๊ฒŒ ๋œ๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด ์ด๋ฒ ํŠธ ํ•ธ๋“ค๋Ÿฌ๋ฅผ ์ธ๋ผ์ธ์œผ๋กœ ๋“ฑ๋กํ•  ๊ฒฝ์šฐ ํ•จ์ˆ˜๋‚ด์˜ this๋Š” ๋ฒ„ํŠผ์ด ์•„๋‹Œ window ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค.

<button onclick="foo()">Button</button>

<script>
    function foo () {
      console.log(this); // window
    }
</script>

๋ฐ˜๋ฉด addEventListener ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ๊ฐ™์€๊ฒฝ์šฐ ์ด๋ฒคํŠธ์— ๋ฐ”์ธ๋”ฉ๋œ ์š”์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค. ์ด๊ฒƒ์€ ์ด๋ฒคํŠธ ๊ฐ์ฒด์˜ currentTarget ํ”„๋กœํผํ‹ฐ์™€ ๊ฐ™๋‹ค.

<button class="btn">Button</button>

<script>
    document.querySelector('.btn').addEventListener('click', function (e) {
      console.log(this); // <button id="btn">Button</button>
      console.log(e.currentTarget); // <button id="btn">Button</button>
      console.log(this === e.currentTarget); // true
    });
</script>

์ œ์ด์ฟผ๋ฆฌ $(this)

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ this์™€ ์ œ์ด์ฟผ๋ฆฌ $(this)๋Š” ๋ช…์นญ์€ ๊ฐ™์„ ์ง€๋ผ๋„ ์‹ค์ œ๋กœ ํ‘œ์‹œ๋˜๋Š” ์ •๋ณด๋Š” ์„œ๋กœ ๋‹ค๋ฅด๋‹ค.

์ œ์ด์ฟผ๋ฆฌ์—์„œ $(this)๋Š” ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ๋‚ด์—์„œ ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•œ ์š”์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์—ญํ• ์„ ํ•œ๋‹ค. ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ this๋Š” ํ˜„์žฌ ์‹คํ–‰ ์ปจํ…์ŠคํŠธ์—์„œ ์ฐธ์กฐ๋˜๋Š” ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ณ , $(this)๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•œ ์š”์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค๋Š” ๋‹ค๋ฅธ์ ์ด ์žˆ๋‹ค.

์•„๋ž˜ ์ฝ”๋“œ ์‹คํ–‰ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ this ๊ฒฝ์šฐ๋Š” ํƒœ๊ทธ๊ฐ€ํ‘œ์‹œ๋˜๊ณ , ์ œ์ด์ฟผ๋ฆฌ $(this)์˜ ๊ฒฝ์šฐ๋Š” ํƒœ๊ทธ ์š”์†Œ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ Object๋กœ ํ‘œ์‹œ๋œ๋‹ค.

<button class="btn">Button</button>

<script>
    $('.btn').click(function() {
        console.log(this);      // ํ˜„์žฌ ์‹คํ–‰ ์ปจํ…์ŠคํŠธ์—์„œ ์ฐธ์กฐ๋˜๋Š” ๊ฐ์ฒด
        console.log($(this));  // ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•œ ์š”์†Œ
    });
</script>

js-jquery-this
this
js-jquery-this
$(this)

์ด๋ ‡๊ฒŒ ๋ณ„๋„๋กœ Object๋กœ ๊ฐ์ŒŒ๊ธฐ ๋•Œ๋ฌธ์— ์ œ์ด์ฟผ๋ฆฌ ์ „์šฉ ๋ฉ”์„œ๋“œ๋“ค์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์ด์œ ์ด๊ธฐ๋„ ํ•˜๋‹ค.

๋งŒ์ผ ์ œ์ด์ฟผ๋ฆฌ ๊ฐ์ฒด์—์„œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ this์™€ ๊ฐ™์€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ–๊ธฐ ์œ„ํ•ด์„œ๋Š” $(this)[0] ๋กœ ๊บผ๋‚ด๋ฉด ๋œ๋‹ค. ์ฆ‰, this  === $(this)[0] ์ธ ๊ฒƒ์ด๋‹ค.

js-jquery-this