Often we find commonality between our classes — repeated code that we’d like to consolidate
Subclasses let us incorporate another class’s state and behavior into our own
This process is often called inheritance, and our subclass is said to “inherit” from a parent class, also called a superclass
Inheritance can avoid duplication and simplify the implementation of a class that needs the same data and functions as another class
class Animal {
constructor(name, weight) {
this._name = name
this._weight = weight
}
eat() {
return `${this._name} is eating!`
}
sleep() {
return `${this._name} is going to sleep!`
}
wakeUp() {
return `${this._name} is waking up!`
}
}
class Gorilla extends Animal {
constructor(name, weight, height) {
super(name, weight)
// property not shared with Animal class
this._height = height
}
get height() {
return this._height
}
climbTrees() {
return `${this._name} is climbing trees!`
}
poundChest() {
return `${this._name} is pounding its chest!`
}
showVigour() {
return `${this.eat()} ${this.poundChest()}`
}
dailyRoutine() {
return `${this.wakeUp()} ${this.poundChest()} ${this.eat()} ${this.sleep()}`
}
}
const gorilla = new Gorilla('George', '160Kg')
console.log(gorilla.eat())
console.log(gorilla.poundChest())
console.log(gorilla.sleep())
console.log(gorilla.height)
console.log(gorilla.dailyRoutine())