Private and Protected Constructors

A class constructor may be marked private or protected.A class with private constructor cannot be instantiated outside the class body, and cannot be extended.A class with protected constructor cannot be instantiated outside the class body, but can be extended.

Example

  1. class Singleton {
  2. private static instance: Singleton;
  3. private constructor() { }
  4. static getInstance() {
  5. if (!Singleton.instance) {
  6. Singleton.instance = new Singleton();
  7. }
  8. return Singleton.instance;
  9. }
  10. }
  11. let e = new Singleton(); // Error: constructor of 'Singleton' is private.
  12. let v = Singleton.getInstance();