mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
feat(curriculum): add interactive editors to class inheritance lesson (#63866)
This commit is contained in:
committed by
GitHub
parent
3081b33dbf
commit
b932e80740
+47
-12
@@ -4,10 +4,8 @@ title: What Is Class Inheritance, and How Does It Work?
|
||||
challengeType: 19
|
||||
dashedName: what-is-class-inheritance-and-how-does-it-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let's learn about inheritance and how it works in JavaScript.
|
||||
|
||||
# --interactive--
|
||||
|
||||
In programming, inheritance allows you to define classes that inherit properties and methods from other classes.
|
||||
|
||||
@@ -72,14 +70,32 @@ console.log(myCar.year);
|
||||
myCar.honk();
|
||||
```
|
||||
|
||||
Here is the output:
|
||||
Here is the full example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
freeCodeCamp Motors
|
||||
2019
|
||||
Honk! Honk!
|
||||
class Vehicle {
|
||||
constructor(brand, year) {
|
||||
this.brand = brand;
|
||||
this.year = year;
|
||||
}
|
||||
}
|
||||
|
||||
class Car extends Vehicle {
|
||||
honk() {
|
||||
console.log("Honk! Honk!");
|
||||
}
|
||||
}
|
||||
|
||||
let myCar = new Car("freeCodeCamp Motors", 2019);
|
||||
console.log(myCar.brand);
|
||||
console.log(myCar.year);
|
||||
myCar.honk();
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Indeed, the output is correct, so these properties and method are defined in the `Car` instance and you just saved yourself a lot of code repetition by inheriting these properties from the `Vehicle` class.
|
||||
|
||||
In this example, the child class didn't have any additional properties. That's why the class didn't have a constructor, only a method.
|
||||
@@ -131,14 +147,33 @@ console.log(myCar.year);
|
||||
console.log(myCar.numDoors);
|
||||
```
|
||||
|
||||
This is the output:
|
||||
Here is the full example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
freeCodeCamp Motors
|
||||
2019
|
||||
4
|
||||
class Vehicle {
|
||||
constructor(brand, year) {
|
||||
this.brand = brand;
|
||||
this.year = year;
|
||||
}
|
||||
}
|
||||
|
||||
class Car extends Vehicle {
|
||||
constructor(brand, year, numDoors) {
|
||||
super(brand, year);
|
||||
this.numDoors = numDoors;
|
||||
}
|
||||
}
|
||||
|
||||
let myCar = new Car("freeCodeCamp Motors", 2019, 4);
|
||||
console.log(myCar.brand);
|
||||
console.log(myCar.year);
|
||||
console.log(myCar.numDoors);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The main advantages of inheritance are code reusability, modularity, extensibility, and improved code structure.
|
||||
|
||||
By implementing a hierarchy, you can reuse code that you already wrote for a parent class in the child class, avoiding repetition.
|
||||
|
||||
Reference in New Issue
Block a user