aotoyae

[JS] class 클래스 사용법, get & set, Static 정적 메소드 본문

JavaScript

[JS] class 클래스 사용법, get & set, Static 정적 메소드

aotoyae 2024. 1. 4. 20:07

 

 

전에 클래스 사용법 글을 썼었지만 한 번 더 정리해 둔다.

 

💡 새 객체를 쉽게 추가해 주는 class!

class Car {
  constructor(name, year, type, price) {
    this.modelName = name;
    this.modelYear = year;
    this.type = type;
    this.price = price;
  }

  makeNoise() { // 클랙션을 울리는 메서드
    console.log(`${this.modelName} : 빵빵!`);
  }

  makedYear() { // 연도를 말해주는 메서드
    console.log(`${this.modelName} : 나는 ${this.modelYear}년도에 만들어졌어~`);
  }
}

const car1 = new Car("현이 차", 2024, "디젤", 2000);
// Car {modelName: '현이 차', modelYear: 2024, type: '디젤', price: 2000}
const car2 = new Car("진이 차", 2023, "디젤", 1000);
// Car {modelName: '진이 차', modelYear: 2023, type: '디젤', price: 1000}
const car3 = new Car("근이 차", 2022, "디젤", 3000);
// Car {modelName: '근이 차', modelYear: 2022, type: '디젤', price: 3000}
console.log(car1);
console.log(car2);
console.log(car3);

car1.makeNoise(); // 현이 차 : 빵빵!
car2.makeNoise(); // 진이 차 : 빵빵!
car3.makeNoise(); // 근이 차 : 빵빵!

car1.makedYear(); // 현이 차 : 나는 2024년도에 만들어졌어~
car2.makedYear(); // 진이 차 : 나는 2023년도에 만들어졌어~
car3.makedYear(); // 근이 차 : 나는 2022년도에 만들어졌어~

 

💡 객체를 추가할 때 유효성 검사를 해주는 get & set

❗️get & set 을 사용할 때 주의할 점은, this. 뒤에 _ 를 붙여주어야 한다!

this 에 접근하는 프로퍼티 네임에 언더스코어 붙여주기!!

class Car {
  constructor(name, year, type, price) {
    this._modelName = name;
    this._modelYear = year;
    this._type = type;
    this._price = price;
  }

  get name() {
    return this._modelName;
  }
  set name(value) {
    // 입력한 값의 유효성 검사라 생각하면 된다!
    if (value.length <= 0) {
      console.log(`모델명이 입력되지 않았어!`);
      return;
    } else if (typeof value !== "string") {
      console.log(`[ERROR] 이름은 문자여야 해!`);
      return;
    }
    this._modelName = value; // 검증을 넘어가야 setting!
  }

  get year() {
    return this._modelYear;
  }
  set year(value) {
    if (value.length <= 0) {
      console.log(`연도가 입력되지 않았어!`);
      return;
    } else if (typeof value !== "number") {
      console.log(`[ERROR] 연도는 숫자여야 해!`);
      return;
    }
    this._modelYear = value;
  }

  get type() {
    return this._type;
  }
  set type(value) {
    if (value.length <= 0) {
      console.log(`타입이 입력되지 않았어!`);
      return;
    } else if (typeof value !== "string") {
      console.log(`[ERROR] 타입은 문자여야 해!`);
      return;
    }
    this._type = value;
  }

  get price() {
    return this._price;
  }
  set price(value) {
    if (value.length <= 0) {
      console.log(`가격이 입력되지 않았어!`);
      return;
    } else if (typeof value !== "number") {
      console.log(`[ERROR] 가격은 숫자여야 해!`);
      return;
    }
    this._price = value;
  }
}

const car1 = new Car("현이 차", 2024, "디젤", 2000);
// Car {modelName: '현이 차', modelYear: 2024, type: '디젤', price: 2000}
console.log(car1);

car1.name = 888; // [ERROR] 이름은 문자여야 해!
console.log(car1.name); // 현이 차 (바뀌지 않음)

car1.year = "작년"; // [ERROR] 연도는 숫자여야 해!
console.log(car1.year); // 2024 (바뀌지 않음)

car1.type = 0; // [ERROR] 타입은 문자여야 해!
console.log(car1.type); // 디젤 (바뀌지 않음)

car1.price = "오천원"; // [ERROR] 가격은 숫자여야 해!
console.log(car1.price); // 2000 (바뀌지 않음)

 

💡 class 의 상속! overriding 오버라이딩!

부모에게 받은 메서드를 가져와 수정할 수 있다!

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} says!`);
  }
}

const me = new Animal("AOTO");
me.speak(); // AOTO says!

class Dog extends Animal {
  speak() {
    console.log(`${this.name} bark!`);
  }
}

const cutePuppy = new Dog("HAPPY");
cutePuppy.speak(); // HAPPY bark!

 

➕ 한번 더 써보기

class Car {
  constructor(name, year, type, price) {
    this.modelName = name;
    this.modelYear = year;
    this.type = type;
    this.price = price;
  }

  makeNoise() {
    console.log(`${this.modelName} : 빵빵!`);
  }

  makedYear() {
    console.log(`${this.modelName} : 나는 ${this.modelYear}년도에 만들어졌어~`);
  }
}

const car1 = new Car("현이 차", 2024, "디젤", 2000);
// Car {modelName: '현이 차', modelYear: 2024, type: '디젤', price: 2000}
console.log(car1);

car1.makeNoise(); // 현이 차 : 빵빵!
car1.makedYear(); // 현이 차 : 나는 2024년도에 만들어졌어~

class ElectricCar extends Car {
  // 이미 전기차니까 type 은 없어도 된다!
  constructor(name, year, price, chargeTime) {
    // type 을 지우고 충전 시간 추가
    // type 을 변경(제거)한 걸 Car(부모 class) 에게도 알려주기!
    super(name, year, "전기차", price); // 부모의 counstructor 이지만 "전기차" 를 고정!

    // 추가한건 부모 때와 똑같이 설정!
    this.chargeTime = chargeTime;
  }

  makeNoise() {
    console.log(`${this.modelName} : 나는 전기차야! 빵빵!`);
  }
}

const electricCar1 = new ElectricCar("균이 전기차", 2021, 4000, 60);
// ElectricCar {modelName: '균이 전기차', modelYear: 2021, type: '전기차', price: 4000}
console.log(electricCar1);
electricCar1.makedYear(); // 균이 전기차 : 나는 2021년도에 만들어졌어~ (그대로 상속)
electricCar1.makeNoise(); // 균이 전기차 : 나는 전기차야! 빵빵! (변경해서 가져옴)

console.log(`충전은 ${electricCar1.chargeTime}분이 걸려!`); // 충전은 60분이 걸려!
electricCar1.chargeTime = 20; // 충전 시간 변경
console.log(`충전은 ${electricCar1.chargeTime}분이 걸려!`); // 충전은 20분이 걸려!

 

💡 Static Method 정적 메소드

❗️static 을 이용하면 객체(인스턴스) 를 따로 추가하지 않아도 된다!

바로바로 사용하고 싶을 때 ~ 다량으로 안전하고 정확하게 ~

class Calculator {
  static add(a, b) {
    console.log("더하기를 해보자~");
    return a + b;
  }

  static minus(a, b) {
    console.log("빼기를 해보자~");
    return a - b;
  }
}

console.log(Calculator.add(3, 5)); // 8
console.log(Calculator.minus(3, 5)); // -2

 

 

 

✳️ 아직 써보진 않았지만 나중에 잘 활용할 수 있기를 ~