class Person {
public age: number;
public firstName: string;
public lastName: string;
}
위 Person
클래스의 property들에 접근하려면 간단히 아래처럼 할 수 있음.
let person = new Person();
person.age = 26;
유저한테 입력을 받아서 age
property의 값을 할당한다고 하면 입력값이 내가 원하는 값인지 아래처럼 확인을 해줘야하는데 이렇게 계속 하는거는 번거로움.
if( inputAge > 0 && inputAge < 200 ) {
person.age = inputAge;
}
따라서 setter
와 getter
를 사용해서 클래스의 property를 제어가능함.
getter
method는 property의 값을 리턴해줌. accessor라고도 불림setter
method는 property의 값을 갱신하게 해줌. setter
는 mutator라고도 함.getter
method는 get
이라는 키워드로 시작하고 setter
method는 set
이라는 키워드로 시작함.
class Person {
private _age: number;
private _firstName: string;
private _lastName: string;
public get age() {
return this._age;
}
public set age(theAge: number) {
if (theAge <= 0 || theAge >= 200) {
throw new Error('The age is invalid');
}
this._age = theAge;
}
public getFullName(): string {
return `${this._firstName} ${this._lastName}`;
}
}
위 코드는 다음과 같이 작동함
age
, firstName
, lastName
property의 접근 제어자를 public
에서 private
으로 바꿔줌age
property를 _age
로 바꿈_age
에 대한 getter와 setter 메소드를 만들어줌. setter 메소드에서는 _age
에 값을 할당하기 전에 적절한 입력값인지 확인해줌.이렇게 만든 age
setter메소드는 다음과 같이 접근가능함.
let person = new Person();
person.age = 10;
위에서 볼 수 있는 것처럼 setter
는 일반 메소드 처럼 ()가 필요없음. person.age
를 했을때 age
setter 메소드가 불러와짐.
person.age = 0;
위처럼 적절하지 않은 age값을 할당하면 에러가나옴.
person.age
로 접근하면 age
getter가 불러와짐
console.log(person.age);
아래 코드는 firstName와 lastName에도 getter
와 setter
를 적용했음.
class Person {
private _age: number;
private _firstName: string;
private _lastName: string;
public get age() {
return this._age;
}
public set age(theAge: number) {
if (theAge <= 0 || theAge >= 200) {
throw new Error('The age is invalid');
}
this._age = theAge;
}
public get firstName() {
return this._firstName;
}
public set firstName(theFirstName: string) {
if (!theFirstName) {
throw new Error('Invalid first name.');
}
this._firstName = theFirstName;
}
public get lastName() {
return this._lastName;
}
public set lastName(theLastName: string) {
if (!theLastName) {
throw new Error('Invalid last name.');
}
this._lastName = theLastName;
}
public getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
위에서 한 것처럼 setter
는 값을 property에 할당하기 전에 적합한 값인지 확인할때 유용함. 추가적으로 아래처럼 복잡한 것도 할 수 있음.
class Person {
// ... other code
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
public set fullName(name: string) {
let parts = name.split(' ');
if (parts.length != 2) {
throw new Error('Invalid name format: first last');
}
this.firstName = parts[0];
this.lastName = parts[1];
}
}
getter
method가 firstName이랑 lastName을 이어서 리턴해줌setter
method가 full name을 first last
형식의 스트링으로 받아서 first
는 firstName에 저장하고last
는 lastName에 저장함이제 아래처럼 fullname
setter와 getter를 일반적인 클래스 property처럼 접근가능함.
let person = new Person();
person.fullname = 'John Doe';
console.log(person.fullName);