编辑:这个问题不同于如何扩展一个类而不必在 ES6 中使用超级?- 虽然答案是相关的,但这显然是一个不同的问题。它涉及到一个特定的错误,并且两大类参与Person
和CreationEvent
实际上并不相互继承。
我有两个 ES6 类,Person
并且CreationEvent
(CreationEvent
继承自Event
)。我希望new CreationEvent
在我制作 a时制作 a new Person
(因为这CreationEvent
是个人帐户历史中事件的一部分)。
运行new CreationEvent()
它自己的工作正常。但是我不能运行new Person()
。
即使使用简化版本的代码仍然失败:
class Event {
constructor() {
this.time = Date.now()
this.tags = []
}
}
class CreationEvent extends Event {
constructor() {
this.description = "Created"
}
}
class Person {
constructor(givenName, familyName, email) {
var creationEvent = new CreationEvent()
}
}
运行new Person()
返回
ReferenceError:在访问“this”或从派生构造函数返回之前,必须在派生类中调用超级构造函数
如何在另一个对象的构造函数中创建一个新的 ES6 对象?
您需要super()
在CreationEvent
类中调用,因为它扩展了Event
类并且需要初始化。像这样:
class CreationEvent extends Event {
constructor() {
super();
this.description = "Created"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句