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
super is used in derived constructor or overridden methods.
Last updated
Was this helpful?