Tutorial: Inheritance in JavaScript with Classes
Hey there, friend! In this tutorial, we're going to explore one of the most powerful features of object-oriented programming in JavaScript: Inheritance. You've already learned about classes, and now it's time to take it to the next level.
Task: Create a subclass ElectricCar
that extends the Car
class.
Step 1: Create the Car
class
Open your index.js
file and add the following code:
class Car { constructor(make, model, year) { this.make = make this.model = model this.year = year }
honk() { console.log("Honk honk!") }}
This Car
class has a constructor that takes in make
, model
, and year
as parameters, and a honk
method that outputs "Honk honk!" to the console.
Step 2: Create the ElectricCar
subclass
Now, let's create the ElectricCar
subclass that extends the Car
class. Add the following code below the Car
class:
class ElectricCar extends Car { constructor(make, model, year, batteryCapacity) { super(make, model, year) this.batteryCapacity = batteryCapacity }
charge() { console.log("Charging...") }}
Notice the extends
keyword, which indicates that ElectricCar
is a subclass of Car
. We're also using the super
keyword to call the Car
constructor and pass in the make
, model
, and year
parameters. Additionally, we've added a batteryCapacity
property and a charge
method specific to electric cars.
Step 3: Create an instance of ElectricCar
and test it
Create an instance of ElectricCar
and call its methods:
const myTesla = new ElectricCar("Tesla", "Model S", 2022, 75)myTesla.honk() // Output: Honk honk!myTesla.charge() // Output: Charging...
Run the code by clicking the "Run" button. You should see the output in the console.
What's happening behind the scenes?
When we create an instance of ElectricCar
, it inherits all the properties and methods from the Car
class, including the honk
method. The ElectricCar
class also adds its own properties and methods, like batteryCapacity
and charge
. This is the power of inheritance!
Real-world example:
Think of a car manufacturer like Tesla, which produces both gas-powered and electric cars. The Car
class represents the common characteristics of all cars, while the ElectricCar
subclass represents the specific features of electric cars. By using inheritance, we can create a hierarchy of classes that share common properties and methods, making our code more organized and efficient.
You've now learned about inheritance in JavaScript! Pat yourself on the back, friend!
What's next?
In the next tutorial, we'll explore Promises in JavaScript. Get ready to learn about asynchronous programming!
Run the code again to see the output, and then click the "Next" button to proceed to the next tutorial.
Tests