본문 바로가기
WEB/JS

(js) prototype 상속 연습

by jackWillow 2021. 8. 22.

prototype 상속 기본형 연습

 


function Vehicle(name) {
  this.name = name
  this.isOn = false
}

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

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

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

function Car(name, wheels) {
  Vehicle.call(this, name)
  this.wheels = wheels
}

Car.prototype = Object.create(Vehicle.prototype)

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

function Motorcycle(name, wheels) {
  Vehicle.call(this, name)
  this.wheels = wheels
}

Motorcycle.prototype = Object.create(Vehicle.prototype)

Motorcycle.prototype.drive = function(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
반응형

'WEB > JS' 카테고리의 다른 글

(js)만 나이 계산  (0) 2021.11.05
(js) class 상속 연습  (0) 2021.08.22
(js)조건절에 boolean 대신 쓸 수 있는 값  (0) 2020.10.10
[javascript] pc와 모바일을 구분하고 싶을 때  (0) 2020.02.12
keyCode 229가 뜰 때  (12) 2020.02.05