Last active
May 3, 2019 17:26
-
-
Save zo0m/5d33c111eb9d9efaa9e2d74e268baf37 to your computer and use it in GitHub Desktop.
JavaScript ES6 Class Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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