JS class getter, setter

차유림·2021년 11월 18일
0

class 공부하는 친구가 질문한 내용 정리

class User {
  constructor(age) {
    this.age = age;
  }
  get age() {
    console.log('조회', this._age);
    return this._age;
  }
  // set age(value) {
  //   console.log('설정', value);
  //   this._age = value;
  // }
}

위와 같은 클래스에서 setter 함수를 주석처리했을 때 왜 Type에러가 나나요?

먼저 setter함수가 있을 경우, 동작과정을 살펴보자.

class의 constructor가 먼저 실행될 것이고
this.age 에서 getter함수가 호출
= 에서 할당하기 위해 setter 함수가 호출된다.

🔍 궁금한 점
age가 접근자 프로퍼티라서 getter, setter함수를 호출해야함은 어떻게 아는가?

  • class 내부에서 getter, setter 사용한 프로퍼티는 class의 프로토타입에 등록된다.(mdn 참고)
  • 콘솔을 출력해보면 age 는 prototype 접근자 프로퍼티, _age는 객체의 데이터 프로퍼티인 것을 확인할 수 있다.
const user1 = new User(23);
console.log('prototype', Object.getOwnPropertyDescriptors(User.prototype));
console.log('object', Object.getOwnPropertyDescriptors(user1));
  • constructor 가 실행될때 어떻게 this.age가 데이터 프로퍼티인지 접근자 프로퍼티인지 알 수 있는지는,, class명세를 살펴봐야할 것 같다..

그럼 setter함수를 주석처리 했을 때,
에러가 나는 이유를 알 수 있을 것이다.
에러메세지를 보면 this.age = age 라인에서
getter만 있는 프로퍼티에는 값을 설정할 수 없어~
라고 알려주고 있다.
= 할당에서 setter함수가 호출되는데
이때 setter함수가 정의되지 않았기 때문에 에러가 발생한 것이다.

constructor 안에서 등록된 프로퍼티를 출력해보면
console.log(Object.getOwnPropertyDescriptors(User.prototype));
다음과 같이 setter가 지정되지 않은걸 확인할 수 있다.

이렇게 작성할 일은 없겠지만,
반대로 getter 함수만 주석처리할 경우
에러는 나지 않지만 값 접근시 undefined가 반환된다.

profile
🎨프론트엔드 개발자💻

0개의 댓글