๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป ํ”„๋ก ํŠธ์—”๋“œ/๐Ÿ“š JS

[์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ] This

by megan07 2023. 12. 27.

 

๐Ÿ“Œ This

์ž์‹ ์ด ์†ํ•œ ๊ฐ์ฒด ๋˜๋Š” ์ž์‹ ์ด ์ƒ์„ฑํ•  ์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ž๊ธฐ ์ฐธ์กฐ ๋ณ€์ˆ˜

 

this๋ฅผ ํ†ตํ•ด ์ž์‹ ์ด ์†ํ•œ ๊ฐ์ฒด ๋˜๋Š” ์ž์‹ ์ด ์ƒ์„ฑํ•  ์ธ์Šคํ„ด์Šค์˜ ํ”„๋กœํผํ‹ฐ๋‚˜ ๋ฉ”์„œ๋“œ๋ฅผ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
this ๋ฐ”์ธ๋”ฉ์€ ํ•จ์ˆ˜ ํ˜ธ์ถœ ๋ฐฉ์‹์— ์˜ํ•ด ๋™์ ์œผ๋กœ ๊ฒฐ์ •๋ฉ๋‹ˆ๋‹ค.

ํ•จ์ˆ˜ ํ˜ธ์ถœ ๋ฐฉ์‹

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

2. ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ

3. ์ƒ์„ฑ์ž ํ•จ์ˆ˜ ํ˜ธ์ถœ

4. Function.prototype.apply/call/bind ๋ฉ”์„œ๋“œ์— ์˜ํ•œ ๊ฐ„์ ‘ ํ˜ธ์ถœ

5. ES6, ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ํ˜ธ์ถœ

 

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

์ผ๋ฐ˜ํ•จ์ˆ˜ ํ˜ธ์ถœ this๋Š” ์ „์—ญ ๊ฐ์ฒด์ธ window๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.
-> ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š๋Š” ์ผ๋ฐ˜ ํ•จ์ˆ˜์—์„œ๋Š” this์˜ ์‚ฌ์šฉ์€ ์˜๋ฏธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค

 

function normal(){
  console.log(this); //Window
}

normal();

2. ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ

this๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.

const rectangle = {
  width:10,
  height:5,
  
  getSize(){

    console.log(this); //{width: 10, height: 5, getSize: ƒ}
    return this.width*this.height;
  }
}

console.log(rectangle.getSize()); //50

3. ์ƒ์„ฑ์ž ํ•จ์ˆ˜ ํ˜ธ์ถœ

this๋Š” ์ƒ์„ฑ์ž ํ•จ์ˆ˜๊ฐ€ ์ƒ์„ฑํ•  ์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.

function Rectangle(width, height){
  this.width = width;
  this.height = height;

}

const r1 = new Rectangle(10, 5);
console.log(r1); //Rectangle {width: 10, height: 5}

4. Function.prototype.apply/call/bind ๋ฉ”์„œ๋“œ์— ์˜ํ•œ ๊ฐ„์ ‘ ํ˜ธ์ถœ

ํ•จ์ˆ˜์˜ ์ฒซ ๋ฒˆ์งธ ์ธ์ˆ˜๋กœ ์ „๋‹ฌํ•˜๋Š” ๊ฐ์ฒด๊ฐ€ this์— ๋ฐ”์ธ๋”ฉ๋ฉ๋‹ˆ๋‹ค.

const rectangle = {
  width : 10,
  height : 5,
  getSize(){
    
    console.log(this);
    // {width: 10, height: 5, getSize: ƒ}
    
    function tmp(){
      console.log(this)
    };
    
    tmp(); 	
    // window
    // ์ผ๋ฐ˜ ํ•จ์ˆ˜๋กœ ํ˜ธ์ถœ๋๊ธฐ ๋•Œ๋ฌธ์— this์— ์ „์—ญ ๊ฐ์ฒด๊ฐ€ ๋ฐ”์ธ๋”ฉ๋ฉ๋‹ˆ๋‹ค.
    
    setTimeout(tmp.bind(this), 0); 	
    // {width: 10, height: 5, getSize: ƒ}
    // Function.prototype.bind๋ฅผ ํ†ตํ•ด tmp์—์„œ ์‚ฌ์šฉํ•  this๊ฐ์ฒด๋ฅผ ๋ฐ”์ธ๋”ฉ ํ•ด์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    
    return this.width*this.height;
  }

}


console.log(rectangle.getSize()); //50

ES6, ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ํ˜ธ์ถœ

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ๋‚ด์˜ this๋Š” ์ƒ์œ„ ์Šค์ฝ”ํ”„์˜ this๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.

 

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜ ์ž์ฒด์˜ this ๋ฐ”์ธ๋”ฉ์„ ๊ฐ€์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
-> ์ฝœ๋ฐฑ ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ this๊ฐ€ ์ „์—ญ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์ž์ฃผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

const rectangle = {
  width : 10,
  height : 5,
  getSize(){ 
    
    setTimeout(()=>console.log(this), 0);
    //{width: 10, height: 5, getSize: ƒ}
    
    return this.width*this.height;
  }

}


console.log(rectangle.getSize());

๐Ÿ’ก ํ—ท๊ฐˆ๋ฆฌ์ง€ ๋ง์•„์•ผ ํ•˜๋Š” ๊ฒƒ

this ๋ฐ”์ธ๋”ฉ์€ ํ•จ์ˆ˜ ํ˜ธ์ถœ ์‹œ์ ์— ๊ฒฐ์ •๋˜๊ณ 
๋ ‰์‹œ์ปฌ ์Šค์ฝ”ํ”„๋Š” ํ•จ์ˆ˜๊ฐ€ ์„ ์–ธ๋  ๋•Œ ๊ฒฐ์ •๋ฉ๋‹ˆ๋‹ค.