[자바스크립트] This

Megan·2023년 10월 23일
0

📌 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 바인딩은 함수 호출 시점에 결정되고
렉시컬 스코프는 함수가 선언될 때 결정됩니다.

profile
프론트엔드 개발자입니다

0개의 댓글