๐Ÿงก JavaScript

[JS] ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ this๋ž€?

Genie_. 2025. 4. 6. 18:37
728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“Œthis๋ž€?

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ this๋Š” ํ•จ์ˆ˜๊ฐ€ ์–ด๋–ป๊ฒŒ ํ˜ธ์ถœ๋˜์—ˆ๋Š”์ง€์— ๋”ฐ๋ผ ๋‹ฌ๋ผ์ง€๋Š” ํŠน๋ณ„ํ•œ ํ‚ค์›Œ๋“œ
์ฆ‰, ์ •์˜๋œ ์œ„์น˜๊ฐ€ ์•„๋‹ˆ๋ผ "ํ˜ธ์ถœ๋œ ๋ฐฉ์‹" ์— ๋”ฐ๋ผ this๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋Œ€์ƒ์ด ๋ฐ”๋€๋‹ค.


๐Ÿ“Œ ์ƒํ™ฉ๋ณ„ this ์ •๋ฆฌ

1. ์ผ๋ฐ˜ ํ•จ์ˆ˜ ํ˜ธ์ถœ

function showThis() {
  console.log(this);
}

showThis(); // ๋ธŒ๋ผ์šฐ์ € ํ™˜๊ฒฝ: window, strict ๋ชจ๋“œ: undefined
  • ์ผ๋ฐ˜ ํ•จ์ˆ˜์—์„œ this๋Š” ์ „์—ญ ๊ฐ์ฒด(window) ๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.
  • ๋‹จ, "use strict" ๋ชจ๋“œ์—์„  undefined๊ฐ€ ๋œ๋‹ค.

2. ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๋กœ ํ˜ธ์ถœ

const user = {
  name: 'Alice',
  sayHi() {
    console.log(this.name);
  }
};

user.sayHi(); // "Alice"
  • ๊ฐ์ฒด ์•ˆ์—์„œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด this๋Š” ๊ทธ ๊ฐ์ฒด ์ž์‹ ์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค.

3. ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

const user = {
  name: 'Bob',
  sayHi: () => {
    console.log(this.name);
  }
};

user.sayHi(); // undefined (๋˜๋Š” ์ „์—ญ name)
  • ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋Š” ์ž์‹ ๋งŒ์˜ this๋ฅผ ๊ฐ€์ง€์ง€ ์•Š๋Š”๋‹ค.
  • ์ •์˜๋œ ์‹œ์ ์˜ ์™ธ๋ถ€ ์Šค์ฝ”ํ”„์˜ this๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

4. ์˜ˆ์ œ ๋น„๊ต

const name = "์ „์—ญ ์ด๋ฆ„";

const user = {
  name: "๊ฐ์ฒด ์ด๋ฆ„",
  sayHi1: function () {
    console.log("sayHi1:", this.name);
  },
  sayHi2: () => {
    console.log("sayHi2:", this.name);
  }
};

user.sayHi1(); // "sayHi1: ๊ฐ์ฒด ์ด๋ฆ„"
user.sayHi2(); // "sayHi2: ์ „์—ญ ์ด๋ฆ„"
  • sayHi1: ์ผ๋ฐ˜ ํ•จ์ˆ˜ → this๋Š” ํ˜ธ์ถœํ•œ ๊ฐ์ฒด user
  • sayHi2: ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ → this๋Š” ์™ธ๋ถ€ ์Šค์ฝ”ํ”„(์ „์—ญ)

5. setTimeout๊ณผ this

const user = {
  age: 25,
  getAge() {
    console.log(this.age);
  }
};

setTimeout(user.getAge, 1000); // undefined

setTimeout์€ user.getAge๋ฅผ ์ผ๋ฐ˜ ํ•จ์ˆ˜์ฒ˜๋Ÿผ ํ˜ธ์ถœํ•ด์„œ this๊ฐ€ ๋ฐ”๋€œ

ํ•ด๊ฒฐ๋ฐฉ๋ฒ• 

setTimeout(() => user.getAge(), 1000);       // 25
setTimeout(user.getAge.bind(user), 1000);    // 25

6. ํ•จ์ˆ˜ ์™ธ๋ถ€์—์„œ ํ• ๋‹นํ•œ ๊ฒฝ์šฐ

function hello() {
  console.log("hello", this);
}

const obj = {
  say: hello
};

obj.say();     // obj
hello();       // window (or undefined in strict mode)
728x90
๋ฐ˜์‘ํ˜•