class A{
constructor(){
this.name=\"A\";
}
M1(){
return \"M1\";
}
}
class B extends A{
constructor(){
this.id=\"B\";
}
You must call super's constructor.When you call the base class constructor it creates the this
and then you can use this
.
class A{
constructor(){
this.name="A";
}
M1(){
return "M1";
}
}
class B extends A{
constructor(){
super();
this.id="B";
}
M2(){
return "M2";
}
}
UPDATED:
The reason why you need to call the super-constructor from a derived class constructor is due to where ES6 allocates instances – they are allocated by/in the base class (this is necessary so that constructors can be subclassed that have exotic instances, e.g. Array):
// Base class
class A {
// Allocate instance here (done by JS engine)
constructor() {}
}
// Derived class
class B extends A {
constructor() {
// no `this` available, yet
super(); // receive instance from A
// can use `this` now
}
}
// Derived class
class C extends B {
constructor() {
// no `this` available, yet
super(); // receive instance from B
// can use `this` now
}
}
Thanks to Axel Rauschmayer.
For more see here https://esdiscuss.org/topic/super-on-class-that-extends