5.5 JavaScript 상속(Inheritance)과 instanceof

지구·2023년 7월 20일
0

JavaScript

목록 보기
29/30

상속의 개념

//운송수단
class Vehicle {
	constructor(acceleration = 1) {
		this.speed = 0
		this.acceleration = acceleration
	}
	accelerate() {
		this.speed += this.acceleration
	}
	decelerate () {
		if (this.speed <= 0) {
			console. log ('정지!')
			return
		}
		this.speed -= this.acceleration
	}
}

// 자전거: 운송수단 클래스를 상속
class Bicycle extends Vehicle {
	constructor(price = 100, acceleration) {
		super(acceleration)
		this.price = price
		this.wheel = 2
	}
}

const bicycle = new Bicyle(300, 2)
console.log(biycle)
// {
//  acceleration: 2,
//  price: 300,
//  speed: 0,
//  wheel: 2
// }
bicycle.accelerate()
console.log(biycle)
// {
//  acceleration: 2,
//  price: 300,
//  speed: 1,
//  wheel: 2
// }
bicycle.accelerate()
console.log(biycle)
// {
//  acceleration: 2,
//  price: 300,
//  speed: 2,
//  wheel: 2
// }

// 자동차: 자전거 클래스를 상속
class Car extends Bicycle {
	constructor(license, price, acceleration) {
		super (price, acceleration)
		this.license = license
		this.wheel = 4
	}
	// 오버라이팅(Overriding) - 재정의
	accelerate() {
		// 면허가 있어야하지만 가속할 수 있음
		if(!this.license) {
			console.error('무면허!')
			return
		}
		this.speed += this.acceleration
		console.log('가속!', this.speed)
	}
}

const carA = new Car(true, 7000, 10)
const carB = new Car(false, 4000, 6)
carB.accelerate() // '무면허!'라고 에러 발생

// 보트
class Boat extends Vehicle {
	constructor (price, acceleration) {
		super (acceleration)
		this.price = price
		this.motor = 1
	}
}

const boat = new Boat(10000, 5)

instanceof

console.log(bicycle instanceof Bicycle) // true
console.log(bicycle instanceof Vehicle) // true

console.log(carA instanceof Car) // true
console.log(carB instanceof Car) // true
console.log(carA instanceof Bicycle) // true
console.log(carB instanceof Vehicle) // true

console.log(boat instanceof Boat) // true
console.log(boat instanceof Bicycle) // false

어떤 클래스를 상속받은 인스턴스인지 확인할 수 있다.

profile
프론트엔트 개발자입니다 🧑‍💻

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

정말 좋은 정보 감사합니다!

답글 달기