更新时间:2022-12-01 09:21:31
你必须调用 super的构造函数。当你调用基类构造函数时,它会创建这个
和然后你可以使用这个
。
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";
}
}
更新:
你需要从派生类构造函数调用超构造函数的原因是由于ES6分配实例的地方 - 它们是由/在基类中分配的(这是必要的)这样构造函数可以被子类化,具有异常实例,例如Array):
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
}
}
感谢 Axel Rauschmayer 。
欲了解更多信息,请点击此处 https://esdiscuss.org/topic/super-on-class-that-extends