- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Calling the function
- Class
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Else
- Else if
- Equality operator
- Extends
- Filter
- For Loops
- Function
- Function name
- Greater than
- Head element
- If statement
- Less than
- Map
- Methods
- Numbers
- Overriding methods
- Parameters
- Reduce
- Removing an element
- Replace
- Sort
- Splice
- Strings
- Substring
- Title
- While Loops
JAVASCRIPT
JavaScript Class Extends: Extending Classes in JS
In JavaScript, the extends
keyword in class declarations creates a class as a child of another class. extends
is a fundamental part of JavaScript's class inheritance, which allows for the extension and reuse of existing classes.
How to Use the Extends Keyword in JavaScript
The syntax for using the extends
keyword involves declaring a class as a subclass of another. In doing so, the subclass inherits methods from the parent class.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
super.speak(); // Calls the speak method from the parent class
console.log(`${this.name} barks.`);
}
}
extends
: The keyword to declare that one class is a subclass of another.super()
: The special function to call the constructor of the parent class.
When to Use the Extends Keyword
You need the extends
keyword to create a new class based on an existing class.
Creating Hierarchies
You can use extends
to build class hierarchies to represent real-world relationships, improving code readability and reuse.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(side) {
super(side, side);
}
}
Adding or Modifying Behavior
Also, you can extend a class to add new methods or modify existing ones to provide new functionality.
class BasicAccount {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
}
class InterestAccount extends BasicAccount {
addInterest(rate) {
this.balance += this.balance * rate / 100;
}
}
Utilizing Interfaces
You can utilize inheritance to process objects of different classes through a single interface.
class Shape {
draw() {
console.log('Drawing a shape');
}
}
class Circle extends Shape {
draw() {
super.draw();
console.log('Drawing a circle');
}
}
Examples of Using the Extends Keyword in JavaScript
User Roles in an Application
Using extension, an application with different access levels might create user roles with specific permissions.
class User {
login() {
console.log('User logged in');
}
}
class Admin extends User {
manageUsers() {
console.log('Admin managing users');
}
}
Error Classes in Libraries
A JavaScript library might create custom error handling by extending the native Error
class.
class DatabaseError extends Error {
constructor(message) {
super(message);
this.name = "DatabaseError";
}
}
UI Components
Specialized UI components often extend a basic component class, adding features and functionality.
class Component {
constructor(name) {
this.name = name;
}
init() {
console.log(`Initializing component: ${this.name}`);
}
}
class Button extends Component {
click() {
console.log(`Button ${this.name} clicked`);
}
}
Learn More About the Extends Keyword
Method Overriding and Using super
When extending a class, you often override methods of the parent class to alter or enhance their behavior. Using the super
keyword, you can call the same method from the parent class. In doing so, you can ensure that the original functionality triggers along with the new behavior.
class Vehicle {
start() {
console.log('Vehicle engine started');
}
}
class Car extends Vehicle {
start() {
super.start(); // Calls the start method from Vehicle
console.log('Car engine started with enhanced features');
}
}
Mixins for Multiple Inheritance-like Behavior
While JavaScript has no direct support for multiple inheritance, you can use mixins to simulate this feature. Mixins allow objects to draw from multiple sources, bringing together functionality from different classes.
let SerializableMixin = Base => class extends Base {
serialize() {
return JSON.stringify(this);
}
};
let ActivatableMixin = Base => class extends Base {
activate() {
console.log('Activated');
}
deactivate() {
console.log('Deactivated');
}
};
class User {
constructor(name) {
this.name = name;
}
}
class SuperUser extends SerializableMixin(ActivatableMixin(User)) {
// SuperUser now has both serialization and activatable capabilities
}
let user = new SuperUser("Jane");
user.activate(); // From ActivatableMixin
console.log(user.serialize()); // From SerializableMixin
Advanced Polymorphism
Inheritance and the extends
keyword enable polymorphism in JavaScript. Using polymorphism, a method can perform different functions depending on the object it belongs to. This is especially useful in complex systems where behavior varies significantly between object types.
class Shape {
draw() {
console.log('Drawing a generic shape');
}
}
class Circle extends Shape {
draw() {
console.log('Drawing a circle');
}
}
class Square extends Shape {
draw() {
console.log('Drawing a square');
}
}
function renderShapes(shapes) {
shapes.forEach(shape => shape.draw());
}
renderShapes([new Circle(), new Square()]);
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.