Inheritance
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 24 of 56.
Inheritance in JavaScript OOP is a way for one class to gain access to all the properties and methods from another class.
Let's look at an example. Create a parent class:
class Vehicle {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
drive() {
console.log("Driving!");
}
}Now create a child class that inherits from Vehicle:
// Car inherits from Vehicle
class Car extends Vehicle {
honk() {
console.log("Beep beep!");
}
}Create an instance of the child class:
const myCar = new Car("Toyota", "Camry");Access properties and methods:
console.log(myCar.brand); // "Toyota" - inherited from Vehicle
console.log(myCar.model); // "Camry" - inherited from Vehicle
// Car can access Vehicle's methods
myCar.drive(); // "Driving!" - inherited from Vehicle
// Car also has its own methods
myCar.honk(); // "Beep beep!" - specific to CarChallenge
You're given an Animal class and a Dog class that inherits from it. Your task is to create a myDog object with name "Buddy" and age 3.
Cheat sheet
Inheritance allows one class to gain access to properties and methods from another class using the extends keyword.
Parent class:
class Vehicle {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
drive() {
console.log("Driving!");
}
}Child class inheriting from parent:
class Car extends Vehicle {
honk() {
console.log("Beep beep!");
}
}The child class inherits all properties and methods from the parent class and can also have its own:
const myCar = new Car("Toyota", "Camry");
console.log(myCar.brand); // "Toyota" - inherited
myCar.drive(); // "Driving!" - inherited
myCar.honk(); // "Beep beep!" - own methodTry it yourself
import { Dog } from './animal.js';
// TODO: Create myDog object with name "Buddy" and age 3.
// Test code - don't modify
console.log(myDog.name); // Should output "Buddy"
console.log(myDog.age); // Should output 3This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge