extends
Creates a subclass that inherits the parent's properties and methods.
Available since: ES2015
Syntax
class Child extends Parent { … }Examples
A subclass gets the parent's methods and adds its own:
class Animal {
constructor(name) {
this.name = name;
}
describe() {
return `${this.name} is an animal`;
}
}
class Dog extends Animal {
bark() {
return `${this.name} says woof`;
}
}
const rex = new Dog('Rex');
console.log(rex.describe());
console.log(rex.bark());Output:
Rex is an animal
Rex says woofExtending a built-in class:
class NotFoundError extends Error {
constructor(what) {
super(`${what} not found`);
this.name = 'NotFoundError';
}
}
console.log(String(new NotFoundError('User')));Output:
NotFoundError: User not foundNotes
A class can extend only one class. If the subclass has its own constructor, it must call super(...) first.
See also
- super — Calls the parent class's constructor or method.
- class — Declares a class — a template for objects with shared methods.
- instanceof — Checks whether an object was created by a class (or a subclass).
In the tutorial
- Inheritance — Class inheritance in JavaScript — extends, super, overriding methods and instanceof.