class / this

이재홍·2022년 1월 30일
0

생성자 함수(프로토타입)

{} 리터럴 방식이 아닌 객체(인스턴스) 생성 방법.

function User(first, last) {
  this.firstName = first
  this.lastName = last
}
User.prototype.getFullName = function() {
  return this.firstName + ' ' + this.lastName
} // 생선된 인스턴스들은 프로토타입을 참조한다. (메모리효율)

const user1 = new User('aa', 'lee')
const user2 = new User('bb', 'son')

user1.getFullName() // aa lee
user2.getFullName() // bb son

class

이전에는 생성자 함수와 프로토타입을 이용해 만들던 인스턴스를
클래스를 이용해 묶어주어 보기쉽게 바꿀 수 있습니다. (기능은 같음)

class A {
  constructor(aaa = 'aaa') {
      this.aaa = aaa;
  }
 	
  static isA(a) { // 정적 메소드(클래스로 사용)
    return a instanceof A;
  }

  aa() { // prototype에 들어감
    console.log('aa');
  }
}

class B extends A {
  constructor(aaa, bbb) {
    super(aaa), // 부모 생성자 실행
    this.bbb = bbb;
  }

  bb() {
    super.aa();
    console.log('bb');
  }
}

this

일반 함수는 호출위치(어디서 호출?)에 따라 this가 결정되어 달라진다 (자신만의 this를 그때그때 가짐)
화살표 함수는 자신이 선언된 함수 범위에서 this를 물려받는다. (자신의 this가 없다)

button.addEventListener('click', function() {
  this.textContent; // 클릭
})
// 콜백함수가 호출될때 this 결정

this; // browser의 경우 window
button.addEventListener('click', (e) => {
  this.textContent; // undefined
  e.target.textContent; // 클릭
})
// 선언될 때 this 결정 (부모함수or클래스의 this)

쉽게 생각하면 this를 쓸 때는 일반적으로 일반함수를 쓰는게 좋다. (호출 위치에 따라 원하는 객체의this가능)
하지만 함수내에 함수를 또 호출할 때 등 부모함수의 this물려받고싶다면 화살표함수를 쓰는게 더 간편하다.

https://poiemaweb.com/js-this

0개의 댓글