class get, set 변수앞 _ 입력

IvanSelah·2021년 9월 8일
post-thumbnail
class User {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  get age() {
    return this._age;
  }

  set age(value) {
  	if (value < 0) {
    	throw Error('나이 입력 오류');
    }
    this._age = value;
  }
}

const user = new User("Ivan", "Selah", -1);

console.log(user.age);

constructor안에 this.age => get age()를 호출
constructor안에 = age => set age(value)를 호출

그렇기 때문에 아래와 같이 정의하면 = value => set age(value)를 무한 호출
set age(value) {
this.age = value;
}

✅ 변수명이 달라도 내부적으로 get와 set를 이용하기 때문에 user.age 로 호출가능

이러한 이유로 get set안에 변수이름앞에 _ 를 붙여서 사용

profile
{IvanSelah : ["꿈꾸는", "끊임없이 노력하는", "프론트엔드 개발자"]}

0개의 댓글