Episode 8 of 11
Class Inheritance
Share code between classes using extends — create a subclass that inherits properties and methods from a parent class and adds its own.
Class Inheritance
Inheritance lets a class inherit properties and methods from another class. The child class gets everything from the parent and can add its own unique features.
The extends Keyword
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
login() {
console.log(this.name + ' just logged in');
}
logout() {
console.log(this.name + ' just logged out');
}
}
class Admin extends User {
deleteUser(user) {
users = users.filter(function(u) {
return u.email !== user.email;
});
console.log(user.name + ' was deleted by ' + this.name);
}
}
Using the Subclass
var admin = new Admin('Shaun', 'shaun@example.com');
var user = new User('Mario', 'mario@example.com');
// Admin inherits User methods:
admin.login(); // 'Shaun just logged in' (inherited)
admin.logout(); // 'Shaun just logged out' (inherited)
// Admin has its own method:
admin.deleteUser(user); // 'Mario was deleted by Shaun'
super() — Calling the Parent Constructor
class Admin extends User {
constructor(name, email, role) {
super(name, email); // Call the parent constructor
this.role = role; // Add new property
}
deleteUser(user) {
console.log(user.name + ' deleted by ' + this.role + ' ' + this.name);
}
}
var admin = new Admin('Shaun', 'shaun@example.com', 'super-admin');
console.log(admin.name); // 'Shaun' (from parent)
console.log(admin.role); // 'super-admin' (from Admin)
super() calls the parent class constructor. You must call it before using this in the child constructor.
Inheritance Hierarchy
User (parent)
├── name, email
├── login(), logout()
│
└── Admin (child) extends User
├── Inherits: name, email, login(), logout()
├── Own: role
└── Own: deleteUser()
Key Takeaways
extendscreates a child class that inherits from a parent class- The child gets all parent properties and methods
super()calls the parent constructor — required if the child has its own constructor- Inheritance avoids code duplication between related classes