class 원하는클래스명 {
constructor(파라미터1, 파라미터2){
this.속성명1 = 파라미터1;
this.속성명2 = 파라미터2;
}
//사용자가 속성의 값을 꺼낼때 실행
get 속성명1 {
return this.속성명1 * 2;
}
//사용자가 속성에 값을 저장할때 실행
set 속성명1 (value){
if(value > 0)
this._속성명1 = value;
}
}
클래스를 사용할때 사용자에게 클래스 내부의 속성을 간접접근 시키거나 조건에 맞는
속성 값만 저장이 가능하도록 하게 하기위해 주로 사용하는 키워드인 get, set이다.
class Person {
//생성자 역할을 하는 constructor
constructor(name, age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
//getter
get age(){
return this._age;
}
//setter : class내 속성 값의 제한을 두어야 하는 경우 자주 사용
set age(value){
if(value > 0 && value < 150){
this._age = value;
}
}
//method
Print(){
console.log('이름 : ' + this.name + ' 나이 : ' + this._age);
}
}
let per1 = new Person('철수',20,'남');
let per2 = new Person('영희',30,'여');
per1.Print(); //'이름 : ' + this.name + ' 나이 : ' + this._age
per2.Print();