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
class Singleton {
private static instance: Singleton;
private constructor() { }
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
let e = new Singleton(); // Error: constructor of 'Singleton' is private.
let v = Singleton.getInstance();