Having another class as a static property on a class

后端 未结 2 1276
终归单人心
终归单人心 2021-01-22 12:15

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.

相关标签:
2条回答
  • 2021-01-22 13:02

    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.

    0 讨论(0)
  • 2021-01-22 13:03

    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.

    0 讨论(0)
提交回复
热议问题