🎨 Frontend/JavaScript

🍦Vanilla JS β‘₯ 클래슀 (μžλ°” class VS μžλ°”μŠ€ν¬λ¦½νŠΈ class)

kongmi 2023. 3. 29. 18:02

  • μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œμ˜ class와 μžλ°”μ˜ classλŠ” μœ μ‚¬ν•œ 점이 λ§ŽμŠ΅λ‹ˆλ‹€.
  • 곡톡사항은 λ”°λ‘œ 닀루지 μ•Šκ³ , 차이점에 λŒ€ν•΄μ„œλ§Œ λ‹€λ£¨κ² μŠ΅λ‹ˆλ‹€.

차이점

  • β˜• μžλ°” ν΄λž˜μŠ€λŠ” μΈν„°νŽ˜μ΄μŠ€λ₯Ό μ‚¬μš©ν•˜μ—¬ 닀쀑 상속을 λͺ¨λ°©ν•  수 μžˆμŠ΅λ‹ˆλ‹€λ§Œ,
    🍦 μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” μΈν„°νŽ˜μ΄μŠ€ κ°œλ…μ΄ μ—†μœΌλ―€λ‘œ λ‹€λ₯Έ 방법을 μ‚¬μš©ν•΄μ•Ό ν•©λ‹ˆλ‹€.
  • β˜• μžλ°” ν΄λž˜μŠ€μ—μ„œλŠ” super ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ μƒμœ„ 클래슀의 μƒμ„±μžλ₯Ό λͺ…μ‹œμ μœΌλ‘œ ν˜ΈμΆœν•΄μ•Ό ν•©λ‹ˆλ‹€.
    πŸ¦μžλ°”μŠ€ν¬λ¦½νŠΈ ν΄λž˜μŠ€μ—μ„œλŠ” super ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ μƒμœ„ 클래슀의 'μƒμ„±μž'λ₯Ό ν˜ΈμΆœν•˜λŠ” 것 이외에도, super ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ μƒμœ„ 클래슀의 'λ©”μ†Œλ“œ'λ₯Ό ν˜ΈμΆœν•  수 μžˆμŠ΅λ‹ˆλ‹€.
  • β˜•μžλ°” ν΄λž˜μŠ€μ—μ„œλŠ” μƒμœ„ 클래슀의 λ©”μ†Œλ“œλ₯Ό super ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ μ˜€λ²„λΌμ΄λ”©μ„ λ°©μ§€ν•  수 μžˆμŠ΅λ‹ˆλ‹€λ§Œ,
    πŸ¦μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” μ˜€λ²„λΌμ΄λ”©μ„ λ°©μ§€ν•˜λŠ” ν‚€μ›Œλ“œκ°€ μ—†κΈ° λ•Œλ¬Έμ— λ‹€λ₯Έ 방법을 μ‚¬μš©ν•΄μ•Ό ν•©λ‹ˆλ‹€.

μ˜ˆμ‹œ

class Vehicle {
  constructor(brand, model, year, color, speed) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    this.color = color;
    this.speed = speed;
  }
  getBrand() {
    return this.brand;
  }
  getModel() {
    return this.model;
  }
  getYear() {
    return this.year;
  }
  getColor() {
    return this.color;
  }
  getSpeed() {
    return this.speed;
  }
  accelerate(amount) {
    this.speed += amount;
    console.log(`The ${this.brand} ${this.model} is now going ${this.speed}km/h.`);
  }
  break(amount) {
    this.speed = Math.max(0, this.speed - amount);
    console.log(`The ${this.brand} ${this.model} is now going ${this.speed}km/h.`);
  }
  static getNumberOfWheels() {
    return 0;
  }
}

class Car extends Vehicle {
  constructor(brand, model, year, color, speed, numDoors) {
    super(brand, model, year, color, speed);
    this.numDoors = numDoors;
  }

  getNumDoors() {
    return this.numDoors;
  }
  static getNumberOfWheels() {
    return 4;
  }
}
class Truck extends Vehicle {
  constructor(brand, model, year, color, speed, towingCapacity) {
    super(brand, model, year, color, speed);
    this.towingCapacity = towingCapacity;
  }
  static getNumberOfWheels() {
    return 6;
  }
}

const myCar = new Car("ν˜„λŒ€", "μ œλ„€μ‹œμŠ€G80", 2022, "BLACK", 180, "4");
console.log(myCar.getBrand());
myCar.accelerate(30);
myCar.break(10);
console.log(Car.getNumberOfWheels());

console.log("\n");

const myCar2 = new Truck("κΈ°μ•„", "봉고", 2010, "WHITE", 100, 10000);
console.log(myCar2.getModel());
console.log(myCar2.getColor());
myCar2.accelerate(50);
myCar2.break(80);
console.log(Truck.getNumberOfWheels());