Having another class as a static property on a cla

2019-02-25 14:34发布

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");
  }
};

2条回答
Summer. ? 凉城
2楼-- · 2019-02-25 14:52

Should I just split it up and use a class expression?

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.

查看更多
唯我独甜
3楼-- · 2019-02-25 15:02

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 (each addPage call will be slower.

'use strict';

class EventEmitter {
  emit(s) {
    alert(s);
  }
}

class App extends EventEmitter {
  addPage(name) {
    class Page extends EventEmitter {
      constructor() {
        super();
        this._paragraphs = [];
      }

      addParagraph(text) {
        this._paragraphs.push(text);
        this.emit("paragraph-added");
      }
    }
    this[name] = new Page;
    this.emit("page-added");
  }
}

var app = new App;
app.addPage("myPage");
app.myPage.addParagraph("Some content");

Alternatively, have both classes defined in a module, and only export the App class thus preventing pollution of the global scope.

查看更多
登录 后发表回答