override constructor
✅ case 1:none has constructor
// no constructors
class A {}
class B extends A {}
let b = new B(); // ✅ OK
❌ case 2:returning from derived constructor without calling super()
first
class A2 {}
class B2 extends A2 {
constructor(){
// ---------------------------------------------------
// ⛔ ReferenceError:
// Must call `super()` constructor in derived class
// ☐ before accessing `this` or
// ☑ returning from derived constructor
// ---------------------------------------------------
}
}
let b2 = new B2();
❌ case 3:accessing this
before calling super()
class A3 {}
// (accessing `this` before calling `super()`)
class B3 extends A3 {
constructor(){
// ---------------------------------------------------
// ⛔ ReferenceError:
// Must call `super()` constructor in derived class
// ☑ before accessing `this` or
// ☑ returning from "derived constructor"
// ---------------------------------------------------
this.name = "Joe"
}
}
let b3 = new B3();
✅ case 4:
class A4 {}
class B4 extends A4 {
constructor(){
// ⭐ "derived constructor" expects "parent (base) constructor"
// to create an empty object and assign it to `this`.
super();
// ✅ now it's OK to access `this`.
this.name = "Joe";
}
}
let b4 = new B4();
log(b4.name); // Joe
🔸 default derived constructor
if a class extends another class and has no constructor(), then the following “default” constructor()
is generated:
class B extends A {
constructor(...args) { super(...args) } // ⭐️ auto-generated
}
🔸 derived constructor
When a regular function is executed with
new
, it creates an empty object and assigns it tothis
.But when a derived constructor runs, it doesn’t do this. It expects the parent (base) constructor to do the job.
So a derived constructor must call
super
in order to execute its parent (base) constructor, otherwise the object forthis
won’t be created. And we’ll get an error.
super is used in derived constructor or overridden methods.
Last updated