JavaScript Reference ยท Classes and Modules
extends and inheritance
Reference for the JavaScript extends keyword: subclassing, super() rules, overriding methods, extending built-ins like Array and Error, and mixins.
extends makes one class a subclass of another. Instances of the subclass get the methods of both classes, the subclass's static members inherit from the parent's, and instanceof is true for both. The subclass calls the parent through super: super(...) in the constructor and super.method() in other methods.
Under the hood, extends sets up two prototype links: Child.prototype inherits from Parent.prototype, and Child itself inherits from Parent.
class Animal { speak() { return "..."; } } class Dog extends Animal { speak() { return "Woof"; } }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
class Child extends Parent { constructor(...args) { super(...args); } method() { return super.method(); } static create() { return super.create(); } } const Anonymous = class extends expression {};
The part after extends is any expression that evaluates to a constructor (or null), such as a class, a function, or a call that returns a class.
Exceptions: TypeError if the value after extends is not a constructor (or null) or its prototype is not an object or null; ReferenceError if a derived constructor uses this before calling super(), or returns without calling it.
Usage notes
- Call
super()first. In a derived constructor,thisdoes not exist untilsuper()returns. If you omit the constructor entirely, JavaScript suppliesconstructor(...args) { super(...args); }. - Overriding. A method of the same name in the subclass wins; use
super.method()to reuse the parent's version. - Fields. The parent's fields are created during
super(), and the subclass's fields right after it. - Private members of the parent are not accessible in the subclass. Offer protected-style access through public or static methods.
- Extending built-ins (
Array,Error,Map,Promise,EventTarget) works becausesuper()creates the real built-in object. Methods likemap()return instances of the subclass throughSymbol.species. instanceofchecks the prototype chain:d instanceof Animalis true for aDog.- Mixins are functions that take a base class and return a subclass; they give limited multiple inheritance.
- Prefer composition. Deep hierarchies are rigid. Reach for
extendswhen the child truly is a kind of the parent. extends nullcreates a class whose instances have noObject.prototype; it is rare and its constructor cannot callsuper().
Browser support
extends and super work in all current browsers. Subclassing built-ins also works; very old engines transpiled by Babel may not handle it.