Javascript this사용법

김진영·2024년 5월 9일
0

구름톤 트레이닝

목록 보기
6/8

Javascript에서 this사용법

메소드에서 this 사용 -> 해당 객체를 가르킨다

const audio = {
  title: "a",
  play() {
    console.log("play this", this);
  }, 
};
audio.play();
audio.stop = function () {
  console.log("stop this", this);
};
audio.stop();
```();


위 코드를 console.log에 출력한 결과 값

함수에서 this 사용 -> Window 객체를 가리킨다

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


위 코드를 console.log에 출력한 결과 값

Constructor에서 this 사용 -> 빈 객체를 가리킨다

function Audio2(title) {
  this.title = title; 
  console.log(this);
}
const audio2 = new Audio2("a");


위 코드를 console.log에 출력한 결과 값

const test = { 
  title: "test",
  categories: ["kim", "yun", "park"],
  testCategories() {
    // forEach의 첫 번째 매개변수: 콜백함수, 두 번째: thisArg
    this.categories.forEach(
      function (category) {
        console.log(`title: ${this.title}, category: ${category}`);
        // 함수안에 있는 this -> window object를 가르킨다.
        // window object안에 title이라는 속성이 없이 때문에 undefined가 나옴
      },
      { title: "test" } // 2번째 매개변수에 작성하면 콜백함수에서 this로 참조 됨
    );
  },
};
test.testCategories();


위 코드를 console.log에 출력한 결과 값

화살표 함수 -> this 항상 상위 스코프의 this를 가르킨다 Lexical this라고 함!

const test2 = { 
  title: "test",
  categories: ["kim", "yun", "park"],
  testCategories() {
    this.categories.forEach((category) => {
      console.log(this);
    });
  },
};
test2.testCategories();


위 코드를 console.log에 출력한 결과 값

그동안 this를 많이 사용해 왔지만 이렇게 정리한건 처음이다..! 사용하다 헷갈릴때 마다 봐야겠다

0개의 댓글