함수를 만들어 Object 데이터를 다루는 이유
1. Object자료가 복잡할때 용이
2. Object 자료 수정시 편리, 실수방지, 관리기능
* Getter, Setter
- Get : 데이터를 추출할 함수 앞에 사용
Get은 return 필수 사용, 파라미터 사용 불가
- Set : 데이터를 변경할 함수 앞에 사용
Set은 파라미터가 1개 이상 필수 사용
소괄호를 제거할 수 있음
var person = {
name : 'Park',
age : 30,
get nextAge() {
return console.log(this.age + 1);
},
set setAge(age) {
this.age = parseInt(age);
return console.log(this.age);
},
}
person.nextAge;
person.setAge = '20';
class에서 사용 예시
class person {
constructor() {
this.name = 'Park',
this.age = 20;
}
get nextAge() {
return this.age + 1
}
set setAge(age) {
if(isNaN(age) === false ) {
throw new Error('[ERROR] 숫자를 입력해주세요');
} else {
this.age = age;
}
}
}
var person1 = new person();
* 상속 예시
1. Class 생성 후 Object 생성, 유사한 Object 생성
2. dog class에서 getNextAge()함수를 사용하면 오류, cat calss에서 사용하면 age 추가
class dog {
constructor(animalType, type, color) {
this.animalType = animalType;
this.type = type;
this.color = color;
}
get getDog() {
return console.log(`${this.animalType}의 종은 ${this.type}이며 ${this.color}색이다.`)
}
getNextAge() {
if(this.age !== undefined) {
this.age += 1;
return console.log(`${this.type}에 내년 나이는 ${this.age}세이다.`)
}
throw new Error(`[ERROR] ${this.animalType}는 나이가 없습니다.`)
};
}
var dog1 = new dog('강아지', '말티즈', '흰');
var dog2 = new dog('강아지', '진돗개', '갈');
dog1.getDog;
dog2.getDog;
dog1.getNextAge();
class cat extends dog {
constructor(animalType, type, color, age) {
super(animalType, type, color);
this.age = age;
}
get getCat() {
return console.log(`${this.animalType}의 종은 ${this.type}이며 ${this.color}색이고 ${this.age}세이다.`)
}
getNextAge() {
super.getNextAge();
};
}
var cat1 = new cat('고양이', '코숏', '흰', 5);
var cat2 = new cat('고양이', '러시안블루', '갈', 2);
cat1.getCat;
cat2.getCat;
cat1.getNextAge();
2. Class 생성 후 Object 생성 getter / setter 사용
class Unit {
constructor() {
this.atk = 5;
this.hp = 100;
};
get battlePoint() {
return console.log(`Battle Point: ${this.atk + this.hp}`);
};
set heal(hp) {
this.hp += hp
console.log(`hp: ${hp} 회복했습니다.`)
}
}
var mon = new Unit();
mon.battlePoint;
mon.heal = 50;
mon.battlePoint;
3. getter / setter 사용해서 입력받은 숫자를 홀수와 짝수로 판별하기
var data = {
odd : [],
even : [],
oddOrEven(...number) {
[...number].forEach((number) => number % 2 === 0 ? this.even.push(number) : this.odd.push(number))
},
get getOdd() {
return console.log(this.odd.sort());
},
get getEven() {
return console.log(this.even.sort());
},
get getSortNumber() {
return console.log([...this.odd, ...this.even].sort());
},
}
data.oddOrEven(1,5,4,2,3)
data.getOdd;
data.getEven;
data.getSortNumber;