extends
Creates a derived class that inherits another class’s methods and can extend or override them.
Example
#class Exercise {
constructor(title, points) {
this.title = title
this.points = points
}
describe() {
return `${this.title} (${this.points} pts)`
}
}
class Quiz extends Exercise {
constructor(title, points, questions) {
super(title, points)
this.questions = questions
}
}
const quiz = new Quiz('Loops quiz', 10, 5)
console.log(quiz.describe())
console.log(quiz)
console.log(quiz instanceof Exercise)Definition and usage
#The extends keyword in a class declaration names the base class, the parent. The derived class gets all of its methods and can add its own, or override an inherited one by writing a method with the same name. Underneath, the prototype chain does the work: the derived class’s prototype points to the base class’s prototype.
If the derived class has its own constructor, it must call super(...) before using this for the first time. It’s the parent constructor that creates the object, and only afterward can the derived class add its own fields. When a derived class has no constructor, JavaScript adds a default one that forwards all the arguments to the parent.
After extends can come any expression that returns a constructor, including a built-in class like Error, Array, or Map. You can only inherit from one class. When you want to combine behavior from several sources, composition, keeping other objects in fields, is usually the better choice.
Syntax
#class Child extends Parent {
constructor(...args) {
super(...args)
}
}
class MyError extends Error {}Parameters
#Parent
class
The base class the new class inherits from. It can also be a built-in class, likeErrororArray.
More examples
#class Exercise {
constructor(title) {
this.title = title
}
reward() {
return 5
}
}
class Project extends Exercise {
reward() {
return 25
}
}
const tasks = [new Exercise('Multiple-choice question'), new Project('Portfolio website')]
for (const task of tasks) {
console.log(task.title, task.reward())
}The Project class has no constructor, so JavaScript used the default one, which forwarded the title to the Exercise constructor.
class Student {
constructor(name) {
this.name = name
}
}
class Mentor extends Student {
constructor(name, course) {
this.course = course
super(name)
}
}
try {
new Mentor('Jack', 'React')
} catch (error) {
console.log(error.name)
}The object is only created in the parent constructor, so before super() runs there’s nothing yet to assign to this. The exact error message differs between browsers.
class Playlist extends Array {
totalMinutes() {
return this.reduce((sum, video) => sum + video.minutes, 0)
}
}
const playlist = new Playlist()
playlist.push({ title: 'Intro', minutes: 4 }, { title: 'Loops', minutes: 11 })
console.log(playlist.length)
console.log(playlist.totalMinutes())
console.log(Array.isArray(playlist))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Only inherit when the derived class really is a variant of the base class, for example a quiz is an exercise. When an object merely has another object, for example a player has inventory, choose composition instead.
- In a derived class’s constructor, call
super()right at the start. Usingthisbefore it ends in aReferenceError. - Avoid deep hierarchies. Two or three levels of inheritance is usually a sensible maximum; beyond that, the code gets hard to follow.
Related entries
#- classDefines a class: a template for creating objects that share the same fields and methods.
- superRefers to the base class: calls its constructor or its version of a method.
- instanceofChecks whether an object was created by a given class, or by a class that inherits from it.
- staticMarks a field or method as belonging to the class itself, not to instances created with new.
- #fieldFields and methods prefixed with # are private: only code inside the class can access them.
Spotted a mistake or missing an example? Write to us.