๊ด€๋ฆฌ ๋ฉ”๋‰ด

Bin's Blog

this Keyword ๋ณธ๋ฌธ

JavaScript

this Keyword

hotIce 2023. 8. 30. 19:10
728x90

๐Ÿค” this keyword๋Š” ์–ด๋””์— ์“ฐ์ด๋ƒ?์— ๋”ฐ๋ผ์„œ ๋œปํ•˜๋Š” ์˜๋ฏธ๊ฐ€ ๋‹ฌ๋ผ์ง„๋‹ค. ํ™•์ธํ•ด๋ณด์ž!

 

1๏ธโƒฃ ์ผ๋ฐ˜ํ•จ์ˆ˜

์ผ๋ฐ˜(์ „์—ญ)ํ•จ์ˆ˜์—์„œ ์“ฐ๋ฉด this๋Š” window๋ฅผ ๋œปํ•œ๋‹ค.

// ๋ˆˆ์— ๋ณด์ด์ง€ ์•Š์ง€๋งŒ window๋ผ๋Š” ์ „์—ญ๊ฐ์ฒด๊ฐ€ ๊ฐ์‹ธ๊ณ  ์žˆ๋‹ค. 
window: {
    function solution() {
    console.log(this);
    } 
}

// window
solution()

 

2๏ธโƒฃ Strict mode

Strict mode์—์„œ๋Š” ์ผ๋ฐ˜ํ•จ์ˆ˜ ์•ˆ์—์„œ this keyword๋ฅผ ๋ถˆ๋ €์„ ๋•Œ undefined๋ผ๋Š” ๊ฐ’์œผ๋กœ ์ง€์ •ํ•ด์ค€๋‹ค. 

'use strict';

function solution(){
  // undefined
   console.log(this)
}
 solution()

 

 

3๏ธโƒฃ Object๋‚ด ํ•จ์ˆ˜ ์•ˆ์—์„œ this

ํ˜ธ์ถœํ•œ ์ž๊ธฐ ์ž์‹ ์„ ํฌํ•จํ•œ ๊ทธ ํ•จ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” Object๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค. 

let object = {
  data : "Kim",
  ํ•จ์ˆ˜() {
    console.log(this);
  }
}

// object = { data: "kim" ...}
object.ํ•จ์ˆ˜();

 

4๏ธโƒฃ Arrow function

์ƒ์œ„ ์š”์†Œ์— ์žˆ๋Š” this๋ฅผ ๋ฌผ๋ ค ๋ฐ›์•„์„œ ์“ฐ๊ฒ ๋‹ค๋Š” ๋œป์ด๋‹ค. 

const object = {
  name: "hobin",
  speak() {return `My name is ${this.name}`}
}

// My name is hobin ์ถœ๋ ฅ
object.speak();

 

 

5๏ธโƒฃ Class

ํด๋ž˜์Šค ์•ˆ์—์„œ ์“ฐ๋ฉด ์ƒˆ๋กœ ์ƒ์„ฑ๋˜๋Š” object๋ฅผ ๋œปํ•œ๋‹ค. 

let object = {}

function machine() {
  // ์ƒˆ๋กœ ์ƒ์„ฑ๋˜๋Š” object === instance
  this.์ด๋ฆ„ = "kim"
}

// machine {์ด๋ฆ„: "kim"}
let object = new machine();

 

 

6๏ธโƒฃ ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ

์ง€๊ธˆ ์ด๋ฒคํŠธ๊ฐ€ ๋™์ž‘ํ•˜๋Š” ๊ณณ์„ ์˜๋ฏธํ•œ๋‹ค.

document.getElementById("๋ฒ„ํŠผ").addEventListener("click", 
function(e) {
  // ์—ฌ๊ธฐ์„œ this === e.currentTarget
  console.log(this)
  // ์ง€๊ธˆ ์ด๋ฒคํŠธ๊ฐ€ ๋™์ž‘ํ•˜๋Š” ๊ณณ
  console.log(e.currentTarget);
})

 

728x90

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

JS Framework & Library ํŠธ๋ Œ๋“œ  (0) 2023.10.14
Garbage collection  (0) 2023.09.18
๋ฒˆ๋“ค๋ง์ด๋ž€?  (0) 2023.08.26
npm vs yarn  (0) 2023.08.05
XML  (0) 2023.07.31