프로그래밍 언어/JavaScript

[JS] this 키워드

tteokbokki-master 2024. 4. 25. 17:41

this

 

1. 메서드에 this 사용 시

const audio = {
  title: 'a',
  play(){
    console.log('play this', this);
  }
}

audio.play()

 

메서드에서 this를 사용하면 해당 객체를 가리킨다.

 

 

 

 

2. 함수에서 this 사용 시

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

playAudio();

함수에서 this를 사용하면 window 객체를 가리킨다.

 

 

 

 

 

3. 생성자 함수에서 this 사용 시

function Audio(title){
  this.title = title;
  console.log(this);
}

const audio = new Audio('a');

생성자 함수에서 this를 사용하면 빈 객체를 가리킨다.

 

 

 

 

+a

const audio = {
  title: 'audio',
  categories: ['rock', 'pop', 'hiphop', 'jazz'],
  displayCategories(){
    this.categories.forEach(function(category){
      console.log(`title: ${this.title}, category: ${category}`);
    })
  }
}

audio.displayCategories();

이때 forEach 메서드의 console.log에 있는 this.title은 메서드에 있는 것이 아니라 일반 함수 안에 있는 것이기 때문에, 해당 객체를 가리키는 게 아니라 window객체를 가리키게 된다.  그래서 undefined가 나오는 것.

 

 

const audio = {
  title: 'audio',
  categories: ['rock', 'pop', 'hiphop', 'jazz'],
  displayCategories(){
    this.categories.forEach(function(category){
      console.log(`title: ${this.title}, category: ${category}`);
    }, this)
  }
}

audio.displayCategories();

 

하지만 forEach 메서드에서 두 번째 매개변수로 값을 넣어주면,  그 값을 콜백함수에서 this를 통해 참조할 수 있다. 즉 위와 같이 넣으면 title이 제대로 잘 나오는 것을 확인할 수 있다.

 

 

 

 

4. 화살표 함수

const audio = {
  title: 'audio',
  categories: ['rock', 'pop', 'hiphop', 'jazz'],
  displayCategories(){
    this.categories.forEach((category) => {
      console.log(this);
    })
  }

}

audio.displayCategories();

 

화살표 함수 안에 있는 this는 항상 상위 스코프의 this를 가리킨다. 이것을 Lexical this라고 한다.