tc39 / proposal-private-methods

Private methods and getter/setters for ES6 classes
https://arai-a.github.io/ecma262-compare/?pr=1668
345 stars 37 forks source link

Private Constructors #37

Closed LandonSchropp closed 6 years ago

LandonSchropp commented 6 years ago

It would great if there was also a way to create private constructors in JavaScript. I find myself wishing for this when I create static methods that act as constructors.

class DatabaseClient {

  static async connectedClient() {
    let client = new DatabasClient();
    await client.#connect();
    return client;
  }

  async #connect() {
    // Conect to the database...
  }
}

In this example, I don't want the constructor to be called directly because it doesn't make sense to interact with a DatabaseClient that's not connected to the database. I can't move the connect logic into the constructor because it's asynchronous. It would be great to be able to do something like this instead:

class DatabaseClient {

  static async connectedClient() {
    let client = new DatabasClient();
    await client.#connect();
    return client;
  }

  #constructor() {}

  async #connect() {
    // Conect to the database...
  }
}
littledan commented 6 years ago

Private fields and methods named #constructor are banned to make room for this as a follow-on proposal. There are still some details to work out, so it's not included here. You can thank @erights for raising the issue.

LandonSchropp commented 6 years ago

Thanks @erights!

@littledan Thanks for the quick reply. Should I close this issue?