在另一个对象的构造函数中创建新的 ES6 对象失败
Making a new ES6 Object in another Object's constructor fails
编辑:这个问题不同于——虽然答案是相关的,但这显然是一个不同的问题。它涉及到一个特定的错误,涉及Person
和CreationEvent
的两个主要类实际上并不相互继承。
我有两个 ES6 类、Person
和 CreationEvent
(CreationEvent
继承自 Event
)。我希望在创建 new Person
时创建一个 new CreationEvent
(因为 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()
returns
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
如何在另一个对象的构造函数中创建一个新的 ES6 对象?
您需要在 CreationEvent
class 中调用 super()
因为它扩展了 Event
class 并且需要初始化。像这样:
class CreationEvent extends Event {
constructor() {
super();
this.description = "Created"
}
}
编辑:这个问题不同于Person
和CreationEvent
的两个主要类实际上并不相互继承。
我有两个 ES6 类、Person
和 CreationEvent
(CreationEvent
继承自 Event
)。我希望在创建 new Person
时创建一个 new CreationEvent
(因为 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()
returns
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
如何在另一个对象的构造函数中创建一个新的 ES6 对象?
您需要在 CreationEvent
class 中调用 super()
因为它扩展了 Event
class 并且需要初始化。像这样:
class CreationEvent extends Event {
constructor() {
super();
this.description = "Created"
}
}