2024-05-06 20:40:05 +00:00
|
|
|
|
---
|
2024-10-30 17:34:11 +00:00
|
|
|
|
date: 2020-10-08
|
2024-05-06 20:40:05 +00:00
|
|
|
|
id: 3b88db70-6291-45e3-96da-3fb70a43222a
|
|
|
|
|
title: JavaScript Class Inheritance
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
# Example
|
|
|
|
|
|
|
|
|
|
Classes in JavaScript can inherit from each other
|
|
|
|
|
|
|
|
|
|
``` javascript
|
|
|
|
|
class Parent {
|
|
|
|
|
constructor(name, parentChild = "Parent") {
|
|
|
|
|
this.parentChild = parentChild
|
|
|
|
|
this.name = name
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
speak(line) {
|
|
|
|
|
console.log(`${this.parentChild} ${this.name} says '${line}'`)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class Child extends Parent {
|
|
|
|
|
constructor(name){
|
|
|
|
|
super(name, "Child")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let parent = new Parent("Father");
|
|
|
|
|
let child = new Child("Gregory");
|
|
|
|
|
parent.speak("Get off my lawn!");
|
|
|
|
|
child.speak("Make me old man!");
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
The use of the word `extends` indicates that this class shouldn’t be
|
|
|
|
|
directly based on the default [Object](20200826201605-objects) prototype
|
|
|
|
|
but on some other class. This is called the superclass. The derived
|
|
|
|
|
class is the subclass. The superclass's constructor and methods can be
|
|
|
|
|
called by appending `super` in front.
|