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.
I realize that the example is not correct ES2015, since there no such thing as a static class
statement.
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");
}
};
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.You could have your class created inside
addPage
. It will create the "abstraction" I suppose you're looking for, but you'll pay in performance (eachaddPage
call will be slower.Alternatively, have both classes defined in a module, and only export the
App
class thus preventing pollution of the global scope.