this

🤯 상황에 따라 '참조'하는 게 달라짐 🤯

💡 어떤 값을 직접 가지지 않고, 그 값이 저장된 위치(주소)를 가리키는 것

🔹 Method에서의 this➡해당 객체를 가리킴( 참조 )

const audio = {
  title: 'a',
  // 메서드
  play() {
    console.log('paly this', this);
  }
}

// 실행
audio.play();

audio.stop = function() {
  console.log('stop this', this);
}
audio.stop();

이것도 마찬가지로 audio 객체 안에 메서드니까 this는 해당 객체를 가리킴


🔹 함수에서의 this➡Window 객체 참조

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

window 객체가 잘 출력되는 걸 볼 수 있음


🔹 생성자(Constructor) 함수에서의 this➡빈 객체

객체를 만들기 위해 사용하는 함수, new 키워드와 함께 쓰임

이름 대문자로 시작
👉 "이건 생성자야" 라는 의미로 구분하기 쉽게 하기 위한 관례

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

const audioA = new Audio('a');

new를 쓰면 this는 새로 생성된 빈 객체를 가리키고
거기에 title = "a"를 넣었기 때문에 this가 { title: "a" }가 된 거

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

const audioA = new Audio('a');

저부분을 주석 처리하면

빈객체를 가리키게 됨


this가 총 2개 있는데 출력하면 각각 어떤걸 가리킬까❓

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

🎯 this.categories➡['rock', 'pop', 'hiphop']
👉 메서드에서 this 사용하면 audio 객체를 가리키니까 category 하나씩 순회⭕

🎯 this.title➡undefined
메서드 안에서 쓰여서 객체.title 아닌가 생각 할 수 있겠지만
👉 함수에서 쓰인거라 this는 window 객체를 가리킴( title이 당연 없음❌ )

이렇게 { title: 'audio' } 하면 이 콜백 함수에서
this가 { title: 'audio' } 이걸 참조하게 만들게 되는 것🐱‍💻

이젠 undefined 안 뜨고 잘 출력 되는 걸 볼 수 있음😎

this 라고 작성하면 함수에 있는 걸까 아님 메서드에 있는걸까❓

👉 메서드에 있는 거기 때문에 객체를 가리켜서 이렇게 출력됨


➡화살표 함수

const audio = {
  title: 'audio',
  categories: ['rock', 'pop', 'hiphop'],
  dispalyCategories() {
    // 콜백함수에서 화살표함수로 변경
    this.categories.forEach((category) => {
      console.log(this);
    })
  }
}
audio.displayCategories();

화살표 함수 안에 있는 this➡항상 "상위 스코프 this를 참조"( lexical this )🤩

이 화살표 안에 있는 this는 저 this를 가리킴
즉, 저 this는 객체를 가리키기 때문에 화살표 안에 this도 객체를 가리킴

profile
안녕하세요! 퍼블리싱 & 프론트엔드 개발 공부 블로그 입니다!

0개의 댓글