JAVASCRIPT - 중급 8편

MJ·2022년 12월 10일
0

JAVASCRIPT 정리

목록 보기
18/22
post-thumbnail

함수를 만들어 Object 데이터를 다루는 이유

1. Object자료가 복잡할때 용이

2. Object 자료 수정시 편리, 실수방지, 관리기능

* Getter, Setter

- Get : 데이터를 추출할 함수 앞에 사용

Get은 return 필수 사용, 파라미터 사용 불가

- Set : 데이터를 변경할 함수 앞에 사용

Set은 파라미터가 1개 이상 필수 사용

소괄호를 제거할 수 있음

var person = {
    name : 'Park',
    age : 30,
    get nextAge() { // Get 사용
        return console.log(this.age + 1);
    },
    set setAge(age) { // Set 사용
        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; // result: 강아지의 종은 말티즈이며 흰색이다.
dog2.getDog; // result: 강아지의 종은 진돗개이며 갈색이다.
dog1.getNextAge(); // result: "Error: [ERROR] 강아지는 나이가 없습니다."

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; // result: 고양이의 종은 코숏이며 흰색이고 5세이다.
cat2.getCat; // result: 고양이의 종은 러시안블루이며 갈색이고 2세이다.
cat1.getNextAge(); // result: 코숏에 내년 나이는 6세이다.

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; // result: Battle Point: 105
mon.heal = 50; // result: hp: 50 회복했습니다.
mon.battlePoint; // result: Battle Point: 155

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; // result: [1,3,5]
data.getEven; // result: [2,4]
data.getSortNumber; // result: [1,2,3,4,5]
profile
A fancy web like a rose

0개의 댓글