WEB/JavsScript

[JavsScript] Class와 상속

Raymond 2022. 5. 31. 20:21

Class


이렇게 클래스를 만들고, new Car()를 호출하면 내부에서 정의한 메서드가 들어 있는 객체가 생성됩니다. 객체의 기본 상태를 설정해주는 생성자 메서드 constructor()는 new에 의해 자동으로 호출되므로, 특별한 절차 없이 객체를 초기화 할 수 있습니다.

class Car {
  constructor(modelName, price) {
    this.modelName = modelName;
    this.price = price;
  }

  getModelName() {
    return this.modelName;
  }

  getPrice() {
    return this.price;
  }

  setModelName(modelName) {
    this.modelName = modelName;
  }

  setPrice(price) {
    this.price = price;
  }
}

const sonata = new Car("소나타", 35000000);
console.log(sonata.getModelName());
console.log(sonata.getPrice());
sonata.setPrice(36000000);
console.log(sonata.getPrice());

 

Class의 상속


클래스 상속을 사용하면 클래스를 다른 클래스로 확장할 수 있습니다. 기존에 존재하던 기능을 토대로 새로운 기능을 만들 수 있습니다.

 

이제 한발 더 나아가 메서드를 오버라이딩 해봅시다. 특별한 사항이 없으면 class Car class ElectricCar에 있는 메서드를 ‘그대로’ 상속받습니다.

 

키워드 super는 이럴 때 사용합니다.

  • super.method(...)는 부모 클래스에 정의된 메서드, method를 호출합니다.
  • super(...)는 부모 생성자를 호출하는데, 자식 생성자 내부에서만 사용 할 수 있습니다.
// 상속 개념

class ElectricCar extends Car {
  constructor(modelName, price, chargingTime) {
    super(modelName, price); // 부모생성자 호출 즉, new Car("아이오닉","40000000")을 수행한다.
    this.chargingTime = chargingTime;
  }

  getChargingTime() {
    return this.chargingTime;
  }

  setChargingTime(chargingTime) {
    this.chargingTime = chargingTime;
  }
}

const ionic = new ElectricCar("아이오닉", 40000000, 120);
console.log(ionic.getModelName());

 

참고자료

https://ko.javascript.info/class

https://ko.javascript.info/class-inheritance