본문 바로가기
WEB/JS

(js) class 상속 연습

by jackWillow 2021. 8. 22.

class 상속 기본형 연습

class Vehicle {
  constructor(name) {
    this.name = name
    this.isOn = false
  }

  start() {
    this.isOn = true
    console.log(this.name + ' is on')
  }

  turnOff() {
    this.isOn = false
    console.log(this.name + ' turned off')
  }

  drive() {
    if(this.isOn) {
      console.log(this.name + ' is moving')
    } else {
      console.log(this.name + " doesn't start")
    }
  }
}

class Car extends Vehicle {
  constructor(name, wheels) {
    super(name)
    this.wheels = wheels
  }

  drive() {
    if(this.isOn) {
      console.log('I drive ' + this.name + ' with ' + this.wheels +' wheels')
    } else {
      console.log(this.name + " doesn't start")
    }
  }
}

class Motorcycle extends Vehicle {
  constructor(name, wheels) {
    super(name)
    this.wheels = wheels
  }

  drive(helmet) {
    if(!helmet) {
      console.log('You must wear a helmet')
    } else if(this.isOn) {
      console.log('I wear ' + helmet + ' and ride ' + this.name + ' with ' + this.wheels + ' wheels')
    } else {
      console.log(this.name + " doesn't start")
    }
  }
}

const myCar = new Car('My car', 4)
const myMotorcycle = new Motorcycle('My motorcycle', 2)

myCar.drive() // My car doesn't start
myCar.start() // My car is on
myCar.drive() // I drive My car with 4 wheels
myCar.turnOff() // My car turned off

myMotorcycle.start() // My motorcycle is on
myMotorcycle.drive() // You must wear a helmet
myMotorcycle.drive('my helmet') // I wear my helmet and ride My motorcycle with 2 wheels
myMotorcycle.turnOff() // My motorcycle turned off

 

반응형