[JS] this 키워드

2024. 4. 25. 17:41·프로그래밍 언어/JavaScript

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라고 한다. 

'프로그래밍 언어 > JavaScript' 카테고리의 다른 글

[JS] 이벤트 루프  (0) 2024.04.25
[JS] call, apply, bind 메서드  (0) 2024.04.25
[JS] id를 반환받지 않아도 Script에서 바로 지목할 수 있다.  (0) 2024.04.24
[JS] 이벤트 버블링, 이벤트 캡처링  (0) 2024.04.24
브라우저 객체 모델  (0) 2023.09.30
'프로그래밍 언어/JavaScript' 카테고리의 다른 글
  • [JS] 이벤트 루프
  • [JS] call, apply, bind 메서드
  • [JS] id를 반환받지 않아도 Script에서 바로 지목할 수 있다.
  • [JS] 이벤트 버블링, 이벤트 캡처링
tteokbokki-master
tteokbokki-master
공부하며 알아가는 걸 조금씩 정리하고 있어요
  • tteokbokki-master
    용로그
    tteokbokki-master
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 프로그래밍 언어
        • HTML & CSS
        • JavaScript
        • React 기초
        • 파이썬 기초
        • TanStack-Query
        • C언어 기초
        • git
        • 리눅스
        • 코딩테스트 공부
      • 개발 지식
      • 언어학
        • 의미론
      • 회고 및 기록
      • 프로젝트
        • TodoList 만들기
        • 학수고대 프로젝트
      • 기타
        • [JS-0기] 한입 FE 챌린지
        • 서평
  • 인기 글

  • 글쓰기 / 관리
  • hELLO· Designed By정상우.v4.10.3
tteokbokki-master
[JS] this 키워드
상단으로

티스토리툴바