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
}
๐ JavaScript.info
๐ธ 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.
๐ JavaScript.info
super is used in derived constructor or overridden methods.
Last updated