Sub topic 12
Calling Parent Constructors and Methods with super
This chapter assumes you have read the previous chapter on extends and know that a subclass inherits methods through the prototype chain. You should also be comfortable with constructors, instance methods, class fields, and static members. Here we cover the super keyword. It has two forms. super(...) calls the parent constructor, and super.method(...) calls a method on the parent. Each form has its own rules and failure modes.
The Two Forms of super
| Form | Where it is allowed | What it does |
|---|---|---|
| `super(args)` | Only inside the constructor of a class that uses `extends` | Runs the parent constructor, which creates `this` |
| `super.name` / `super.name(args)` | Any method, getter, setter, static method, field initializer, or static block | Looks up `name` on the parent's prototype (or on the parent class, in static code) and calls it with the current `this` |
Using super(...) anywhere else is a SyntaxError, and the engine reports it when it parses the code, before anything runs. A plain function cannot use super.method() either. Only methods defined with method syntax in a class or an object literal can.
super() in a Derived Constructor
In a base class, new creates the object first and then runs the constructor with this already set. A derived class, meaning one that uses extends, works differently. Its this does not exist until the parent constructor has run. Calling super(...) is what runs the parent constructor and binds this.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // creates and initializes `this` via Animal
this.breed = breed; // safe: `this` now exists
}
speak() {
return `${super.speak()} Woof!`;
}
}
const d = new Dog('Rex', 'Beagle');
console.log(d.speak()); // 'Rex makes a sound. Woof!'
console.log(d.name, d.breed); // 'Rex' 'Beagle'Touching this before super()
If you read or write this before super() has run, you get a ReferenceError. The derived this is in a temporal dead zone, the same idea as a let variable used before its declaration.
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
this.lives = 9; // ReferenceError: `this` is not initialized yet
super(name);
}
}
try {
new Cat('Tom');
} catch (err) {
console.log(err.constructor.name); // 'ReferenceError'
}You may run code that does not touch this before super(). Validating or transforming arguments there is common and useful:
class Animal {
constructor(name) {
this.name = name;
}
}
class Parrot extends Animal {
constructor(name) {
const clean = String(name).trim();
if (clean === '') throw new TypeError('name is required');
super(clean);
}
}
console.log(new Parrot(' Polly ').name); // 'Polly'Forgetting super() entirely
A derived constructor that finishes without calling super() also throws a ReferenceError when you run new. Calling super() twice is an error as well, because this is already initialized the second time. There is one exception. A derived constructor may skip super() if it returns an object explicitly. That object becomes the result of new. This pattern is rare and confusing, so avoid it unless you have a specific reason.
The implicit constructor
If a derived class has no constructor, JavaScript supplies one that passes every argument through:
class Animal {
constructor(name) {
this.name = name;
}
}
// Behaves as if it had: constructor(...args) { super(...args); }
class Fish extends Animal {
swim() {
return `${this.name} swims.`;
}
}
console.log(new Fish('Nemo').swim()); // 'Nemo swims.'Leave the constructor out whenever all it would do is forward its arguments. Writing constructor(...args) { super(...args); } by hand adds nothing.
When Derived Fields Are Initialized
Class fields interact with super() in a way that catches many developers. A base class initializes its fields before its constructor body runs. A derived class initializes its fields right after super() returns. As a result, the parent constructor runs while the child's fields do not exist yet.
This ordering breaks a common design, a parent constructor that calls an overridable "hook" method:
class Widget {
constructor() {
this.setup(); // calls the subclass override
}
setup() {}
}
class List extends Widget {
items = [];
setup() {
this.items.push('first'); // items is still undefined here
}
}
try {
new List();
} catch (err) {
console.log(err instanceof TypeError); // true
}When Widget's constructor calls this.setup(), it dispatches to List.prototype.setup. At that moment items = [] has not run yet. You can fix this in three ways. You can call the hook from the subclass constructor after super(). You can move initialization out of the constructor into an explicit init() method. Or you can have the hook create its own state lazily. The cleanest rule is that a constructor should not call methods that subclasses are expected to override.
super.method() for Extending Behavior
When a subclass overrides a method, super.method() gives it access to the parent's version, so it can add to that behavior without copying the code. super.method() passes the current this through. The parent method therefore works on the subclass instance.
class Logger {
format(msg) {
return msg;
}
log(msg) {
return this.format(msg);
}
}
class TimestampLogger extends Logger {
format(msg) {
return `[12:00] ${super.format(msg)}`;
}
}
class LevelLogger extends TimestampLogger {
format(msg) {
return `INFO ${super.format(msg)}`;
}
}
console.log(new LevelLogger().log('started')); // 'INFO [12:00] started'Each super.format call goes up exactly one level from the class where the method was defined. The class of this does not affect it. That is why the chain ends instead of recursing forever.
super works in getters and setters too. Inside an arrow function, it refers to whatever super means in the enclosing method:
class Base {
get label() {
return 'base';
}
greet(n) {
return `hi ${n}`;
}
}
class Child extends Base {
get label() {
return `${super.label}+child`;
}
greetAll(names) {
return names.map((n) => super.greet(n)); // arrow reuses the method's super
}
}
const c = new Child();
console.log(c.label); // 'base+child'
console.log(c.greetAll(['a', 'b'])); // ['hi a', 'hi b']A regular function callback inside greetAll could not use super. It would be a SyntaxError.
super in Static Methods
In static code, super refers to the parent class itself rather than its prototype. As with instance methods, this passes through. If the parent's static method uses this, it gets the subclass:
class Model {
static create(data) {
return Object.assign(new this(), data);
}
}
class User extends Model {
static create(data) {
const user = super.create(data); // `this` inside Model.create is User
user.createdAt = 'now';
return user;
}
}
const u = User.create({ name: 'Ada' });
console.log(u instanceof User, u.name, u.createdAt); // true 'Ada' 'now'How super Is Resolved: The Home Object
Unlike this, super is not decided at call time. When a method is defined, the engine records the object it was defined on, called its home object, and super lookups always start at that object's prototype. Moving a method to a different object does not change what super refers to:
class A {
hello() {
return 'A';
}
}
class B extends A {
hello() {
return `B>${super.hello()}`;
}
}
class C {
hello() {
return 'C';
}
}
C.prototype.hello = B.prototype.hello; // borrow B's method
console.log(new C().hello()); // 'B>A', not 'B>C'This rarely causes problems in normal class code. It does matter when you copy methods between objects with Object.assign or borrow them the way the example does. The copied method keeps calling the original parent.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| `ReferenceError` mentioning `super` or `this` in a constructor | `this` used before `super()`, or `super()` never called | Call `super(...)` first, before any `this` access |
| `SyntaxError: 'super' keyword unexpected here` | `super()` outside a derived constructor, or `super.x` inside a regular `function` | Use an arrow function, or move the code into a method |
| `TypeError` reading a subclass field during construction | Parent constructor called an override before the derived fields were initialized | Do not call overridable methods from constructors |
| Override silently drops parent behavior | Forgot `super.method()` | Call `super.method(...)` and combine its result |
Exercise
A class Base has constructor() { this.ready = true; }. A subclass declares class Sub extends Base { constructor(opts) { this.opts = opts; super(); } }. What happens on new Sub({}), and how do you fix it while still storing opts?
Show answer
It throws a ReferenceError, because this is used before super() has initialized it. Move super() to the first line: constructor(opts) { super(); this.opts = opts; }. Code that does not touch this, such as validating opts, may still run before super().
Exercise
Given class P { constructor() { console.log(this.kind); } } and class Q extends P { kind = 'q'; }, what does new Q() log, and why?
Show answer
It logs undefined. Q's field initializer kind = 'q' runs only after super() returns, but P's constructor reads this.kind during the super() call, before that initializer has run.
Exercise
Write a static method in a subclass Admin extends User that calls User's static create(data) and then sets role = 'admin' on the result. Why will the returned object be an instance of Admin if User.create uses new this()?
Show answer
static create(data) { const a = super.create(data); a.role = 'admin'; return a; }. super.create is called with this set to Admin. new this() inside User.create therefore constructs an Admin.