class A{
constructor(){
this.name="A";
}
M1(){
return "M1";
}
}
class B extends A{
constructor(){
this.id="B";
}
M2(){
return "M2";
}
}
var b = new B();
output:
ReferenceError:未定义
在 B(重复:4:1)
重复:1:9
在 REPLServer.defaultEval (repl.js:262:27)
绑定时 (domain.js:287:14)
在 REPLServer.runBound [as eval] (domain.js:300:12)
在 REPLServer 上。 (repl.js:431:12)
在emitOne (events.js:82:20)
在 REPLServer.emit (events.js:169:7)
在 REPLServer.Interface._onLine (readline.js:211:10)
在 REPLServer.Interface._line (readline.js:550:8)
你必须打电话super's构造函数。当您调用基类构造函数时,它会创建this
然后你可以使用this
.
class A{
constructor(){
this.name="A";
}
M1(){
return "M1";
}
}
class B extends A{
constructor(){
super();
this.id="B";
}
M2(){
return "M2";
}
}
UPDATED:
需要从派生类构造函数调用超级构造函数的原因是 ES6 分配实例的位置 - 它们是由基类/在基类中分配的(这是必要的,以便可以对具有外来实例的构造函数进行子类化,例如 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
}
}
谢谢阿克塞尔·劳施梅尔.
欲了解更多信息,请参见这里https://esdiscuss.org/topic/super-on-class-that-extends
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)