The extends Keyword
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 26 of 56.
The extends keyword in JavaScript is used to create a child class that inherits properties and methods from a parent class.
Let's first create a parent class:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}Now, let's create a child class that extends the parent class:
class Dog extends Animal {
// The Dog class inherits from Animal
}This simple code means that the Dog class now inherits all the properties and methods from the Animal class.
Create a dog instance:
const dog = new Dog('Rex');Call a method inherited from the parent:
console.log(dog.speak()); // Outputs: "Rex makes a noise."The extends keyword creates an inheritance relationship where the child class (Dog) can access and use all the functionality defined in the parent class (Animal).
Challenge
Create a Student class that extends the Person class using the extends keyword and export it.
Cheat sheet
The extends keyword creates a child class that inherits properties and methods from a parent class:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
// Dog inherits from Animal
}
const dog = new Dog('Rex');
console.log(dog.speak()); // Outputs: "Rex makes a noise."The child class can access all properties and methods from the parent class.
Try it yourself
import { Student } from './classes.js';
// Test code - don't modify
const student = new Student("Emma");
console.log(student.greet()); // Should output "Hello, I'm Emma"This 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