问题描述
请阅读下面的示例*,但不要过分注意 EventEmitter
继承,它只是显示了类
语法。
Read the example below*, but don't pay too much attention to the EventEmitter
inheritance, please – it just shows the utility of the class
syntax.
我意识到示例是不正确的ES2015,因为没有这样的事情作为 static class
I realize that the example is not correct ES2015, since there no such thing as a static class
statement.
在ES2015中,这种工作方式最简单的方法是什么?
What would be the most syntactically lean way to make something like this work in ES2015?
class App extends EventEmitter {
addPage(name) {
this[name] = new App.Page;
this.emit("page-added");
}
static class Page extends EventEmitter {
constructor() {
super();
this._paragraphs = [];
}
addParagraph(text) {
this._paragraphs.push(text);
this.emit("paragraph-added");
}
}
}
我应该把它拆分并使用类表达式,如下所示?似乎不那么优雅。
Should I just split it up and use a class expression, like below? Seems less elegant.
class App extends EventEmitter {
addPage(name) {
this[name] = new App.Page;
this.emit("page-added");
}
}
App.Page = class extends EventEmitter {
constructor() {
super();
this._paragraphs = [];
}
addParagraph(text) {
this._paragraphs.push(text);
this.emit("paragraph-added");
}
};
推荐答案
是的,这是要走的路。如果您坚持使用声明,您必须之后进行 App.Page = Page
作业。
Yes, that's the way to go. If you insist on using a declaration, you'd have to make a App.Page = Page
assignment afterwards.
这篇关于在类上有另一个类作为静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!