자바스크립트에서 생성자(constructor)와 getter, setter 각각의 용도를 복습해보았다.
객체 생성과 동시에 호출되며 전달되는 값을 사용하여 속성값을 초기화할 때 사용하며, 생략 가능하다.
class PersonCl {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
}
const minsu = new PersonCl('minsu han', 1999);
getter: 객체 사용자에게 속성값을 간접 접근하도록 할 때 사용함
setter: 조건에 맞는 속성값만 저장하도록 할 때 사용함
class PersonCl {
set setName(name) {
this.name = name;
}
get getName() {
return this.name;
}
}
const minsu = new PersonCl();
// getter/setter는 함수 호출하듯이 괄호를 사용하여 호출할 수 없다
// 왜냐하면 PersonCl 객체 프로토타입의 메소드가 아니기 때문이다.
// setter 호출
minsu.setName = 'minsuhan';
// getter 호출
console.log(minsu.getName);
// getter를 잘못 호출하는 경우
console.log(minsu.getName());
// TypeError: minsu.getName is not a function
아래 예제는 생성자와 getter/setter를 같이 사용하는 예제이다.
위에서 보았듯 setter를 호출하는 표현식이 객체.속성명 = 값이었기 때문에, PersonCl의 생성자 함수 파라미터명과 setter의 함수명을 동일하게 하면, 생성자가 전달받은 값을 setter에게 전달하여 호출할 수 있다.
class PersonCl {
constructor(fullName, birthYear) {
// fullName에 'Jessica Davies'를 전달받으면
// this.fullName = 'Jessica Davies' 형식이 되고
// 이 형식은 fullName setter 함수에 'Jessica Davies'를 전달하여 호출하는 셈이 된다.
this.fullName = fullName;
this.birthYear = birthYear;
}
// setter, getter를 자주 사용하지는 않지만 사용자에게 클래스 내부의 속성을 간접접근시키거나(getter) 조건에 맞는 속성값만 저장하도록 할 때(setter) 주로 사용한다.
set fullName(name) {
console.log(name);
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name!`);
}
get fullName() {
return this._fullName;
// 속성값에 추가적인 작업을 해서 리턴해줄 수도 있다.
// ex) return this._value * 2
}
}
// PersonCl 객체 생성자가 setter에게 'Jessica Davies'를 전달하면 조건을 검사하고 통과한 경우 _fullName 속성에 저장한다.
// 속성명 fullName 앞에 underscore(_)를 붙이는 것은 속성명이 fullName으로 같아 setter가 순환호출되는 것을 막기 위해 이름을 달리 할 때의 convention이다.
const jessica = new PersonCl('Jessica Davies', 1996);
// getter를 호출하여 내부 속성 _fullName에 간접 접근하도록 한다.
console.log(jessica.fullName)