๐ ์๋ฐ์คํฌ๋ฆฝํธ this vs ์ ์ด์ฟผ๋ฆฌ $(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>
์ด๋ ๊ฒ ๋ณ๋๋ก Object๋ก ๊ฐ์๊ธฐ ๋๋ฌธ์ ์ ์ด์ฟผ๋ฆฌ ์ ์ฉ ๋ฉ์๋๋ค์ ์ฌ์ฉํ ์ ์๋ ์ด์ ์ด๊ธฐ๋ ํ๋ค.
๋ง์ผ ์ ์ด์ฟผ๋ฆฌ ๊ฐ์ฒด์์ ์๋ฐ์คํฌ๋ฆฝํธ this์ ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ๊ธฐ ์ํด์๋ $(this)[0] ๋ก ๊บผ๋ด๋ฉด ๋๋ค. ์ฆ, this === $(this)[0] ์ธ ๊ฒ์ด๋ค.