Skip to content

Instantly share code, notes, and snippets.

@zo0m
Last active May 3, 2019 17:26
Show Gist options
  • Save zo0m/5d33c111eb9d9efaa9e2d74e268baf37 to your computer and use it in GitHub Desktop.
Save zo0m/5d33c111eb9d9efaa9e2d74e268baf37 to your computer and use it in GitHub Desktop.
JavaScript ES6 Class Singleton
(function(){
class A {
static getInstance() {
if (!this.hasOwnProperty('_instance')) {
this._instance = new this;
console.log(`new instance of ${this._instance}`);
}
return this._instance;
}
toString() {
return '{A}';
}
}
class B extends A {
toString() {
return '{B}';
}
}
class C extends A {
toString() {
return '{C}';
}
}
class D extends C {
toString() {
return '{D}';
}
}
console.log([
A.getInstance(),
B.getInstance(),
B.getInstance(),
A.getInstance(),
C.getInstance(),
D.getInstance(),
]);
})();
/*
new instance of {A}
new instance of {B}
new instance of {C}
new instance of {D}
[A, B, B, A, C, D]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment