The `extends` keyword in JavaScript is a fundamental part of the class inheritance mechanism, allowing one class to inherit properties and methods from another. This feature is part of the ECMAScript 2015 (ES6) specification and plays a crucial role in object-oriented programming within JavaScript. Understanding how `extends` works is essential for creating reusable and maintainable code in modern web applications.
When a class extends another class, it creates a prototype chain between the two classes. The child class inherits all the properties and methods of the parent class, which can then be overridden or extended with additional functionality. This promotes code reuse and allows developers to build upon existing code rather than starting from scratch.
The basic syntax for using `extends` is straightforward. Here’s a simple example:
class Parent {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // Call the parent class constructor
this.age = age;
}
introduce() {
return `${this.greet()} and I am ${this.age} years old.`;
}
}
const childInstance = new Child('Alice', 10);
console.log(childInstance.introduce()); // Output: Hello, my name is Alice and I am 10 years old.
When a child class extends a parent class, it must call the parent class's constructor using the `super()` function. This is necessary to ensure that the parent class is properly initialized before the child class adds its own properties. Failing to call `super()` will result in a runtime error.
Child classes can override methods from the parent class. This allows for specialized behavior while still retaining the original method's functionality. Here’s an example:
class Parent {
greet() {
return 'Hello!';
}
}
class Child extends Parent {
greet() {
return 'Hi there!';
}
}
const childInstance = new Child();
console.log(childInstance.greet()); // Output: Hi there!
Even after overriding a method, you can still access the parent class's method using `super.methodName()`. This is useful when you want to extend the functionality of a parent method rather than completely replace it.
class Parent {
greet() {
return 'Hello!';
}
}
class Child extends Parent {
greet() {
return `${super.greet()} I am a child.`;
}
}
const childInstance = new Child();
console.log(childInstance.greet()); // Output: Hello! I am a child.
In conclusion, understanding how `extends` works in JavaScript classes is vital for effective object-oriented programming. By leveraging inheritance correctly, developers can create robust and maintainable codebases that are easier to understand and extend over time.