๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

JavaScript

'this' ํ‚ค์›Œ๋“œ์˜ ๋‹ค์–‘ํ•œ ์‚ฌ์šฉ

'this' ํ‚ค์›Œ๋“œ์˜ ๋‹ค์–‘ํ•œ ์‚ฌ์šฉ

  • ๋ณธ์ธ์„ ๋‹ด๊ณ  ์žˆ๋Š” ์˜ค๋ธŒ์ ํŠธ๋ฅผ ํ‘œํ˜„
    • ํ•จ์ˆ˜๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ์˜ค๋ธŒ์ ํŠธ (์˜ค๋ธŒ์ ํŠธ ๋‚ด ํ•จ์ˆ˜(๋ฉ”์„œ๋“œ)์—์„œ ์‚ฌ์šฉ, arrow function ์ผ ์‹œ ํ•จ์ˆ˜๋ฐ–์— ์žˆ๋Š” this๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ)
    • window (์ „์—ญ์— ์„ ์–ธ, ํ•จ์ˆ˜ ์•ˆ์— ์„ ์–ธ(strict ๋ชจ๋“œ์—์„  undefined)) -> ํ•จ์ˆ˜๋‚˜ ๋ณ€์ˆ˜๋ฅผ ์ „์—ญ ๊ณต๊ฐ„์— ๋งŒ๋“ค๋ฉด window(global object)์—์„œ ๋ณด๊ด€ํ•˜๊ธฐ ๋•Œ๋ฌธ
  • constructor์—์„œ์˜ this ํ‚ค์›Œ๋“œ
    • ์ƒˆ๋กœ ์ƒ์„ฑ๋˜๋Š” object(instance)๋ฅผ ์˜๋ฏธ
  • addEventListener์˜ function์—์„œ ์‚ฌ์šฉ ์‹œ
    • e.currentTarget ( e.currentTarget๋Š”? ์ด๋ฒคํŠธ๊ฐ€ ๋™์ž‘ํ•˜๊ณ  ์žˆ๋Š” HTML ์š”์†Œ )

๋ณธ์ธ์„ ๋‹ด๊ณ  ์žˆ๋Š” ์˜ค๋ธŒ์ ํŠธ๋ฅผ ํ‘œํ˜„

let data = {
  testArray: [1, 2, 3],
  testFunc: function () {
    console.log(this); // data ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ถœ๋ ฅ
    data.testArray.forEach(function () {
      console.log(this); // ์˜ค๋ธŒ์ ํŠธ์—์„œ ์„ ์–ธ๋œ this๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ window ์ถœ๋ ฅ
    });
  },
};
data.testFunc();
Object
Window
Window
Window

arrow function ์ผ ์‹œ?

let dataOfArrowFunc = {
  testArrayOfArrowFunc: [1, 2, 3],
  testFuncOfArrowFunc: function () {
    console.log(this); // dataOfArrowFunc ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ถœ๋ ฅ
    dataOfArrowFunc.testArrayOfArrowFunc.forEach(() => {
      console.log(this); // ์ƒ์œ„์˜ this๋ฅผ ๊ฐ€์ ธ์˜ค๋ฏ€๋กœ window๊ฐ€ ์•„๋‹Œ dataOfArrowFunc ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ถœ๋ ฅ
    });
  },
};
dataOfArrowFunc.testFuncOfArrowFunc();
Object
Object
Object
Object

constructor์—์„œ์˜ this ํ‚ค์›Œ๋“œ

function TestConstructor(name) {
  this.name = name;
  this.testFunction = function () {
    console.log(this); // ์ธ์Šคํ„ด์Šค ์ถœ๋ ฅ
    console.log(this.name); // ์ธ์Šคํ„ด์Šค์˜ name ์ถœ๋ ฅ
  };
}

const testInstance = new TestConstructor("testName");
testInstance.testFunction();
TestConstructor
testName

addEventListener์˜ function์—์„œ ์‚ฌ์šฉ ์‹œ

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <butto id="test">test button</butto>
  </body>
</html>
<script>
  document.getElementById("test").addEventListener("click", function (event) {
    console.log(this); // event.currentTarget ์ถœ๋ ฅ
    console.log(event.currentTarget === this); // true ์ถœ๋ ฅ
    let testArray = [1, 2, 3];
    testArray.forEach(function () {
      console.log(this); // addEventListener์—์„œ ์„ ์–ธ๋œ this๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ window ์ถœ๋ ฅ
    });
  });
</script>
<butto id="test">test button</butto>
true
Window
Window
Window

event.currnetTarget vs event.target

event.currnetTarget๋Š” ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ๊ฐ€ ๋ถ€์ฐฉ๋˜์–ด ์žˆ๋Š” ์š”์†Œ, event.target์€ ํด๋ผ์ด์–ธํŠธ๊ฐ€ ํด๋ฆญํ•œ ์š”์†Œ (์ž์‹ ํฌํ•จ)

'JavaScript' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

$(document).ready ์‚ฌ์šฉ  (0) 2022.03.13
var, let, const  (0) 2022.03.12
ES6 ํ•จ์ˆ˜ ๊ธฐ๋Šฅ  (0) 2022.03.11
ajax๋กœ Post ์š”์ฒญํ•˜๊ธฐ  (0) 2022.03.10
์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์ž๋ฃŒ๊ตฌ์กฐ  (0) 2022.03.08