Forked from dmnsgn/SingletonModuleScopedInstance.js
Last active
September 27, 2019 08:28
-
-
Save YozhEzhi/85d1db271b37fab15098aa75c8dc0740 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: constructor returns an instance scoped to the module. With using the `new` operator.
This file contains hidden or 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
let instance; | |
class Singleton { | |
constructor() { | |
if (!instance) { | |
instance = this; | |
} | |
this._type = 'Singleton'; | |
return instance; | |
} | |
singletonMethod() { | |
return 'singletonMethod'; | |
} | |
static staticMethod() { | |
return 'staticMethod'; | |
} | |
get type() { | |
return this._type; | |
} | |
set type(value) { | |
this._type = value; | |
} | |
} | |
export default Singleton; | |
// index.js | |
import Singleton from './Singleton'; | |
// Instantiate | |
const instance2 = new Singleton(); | |
console.log(instance2.type, instance2.singletonMethod()); | |
// Getter/Setter | |
instance2.type = 'type updated'; | |
console.log(instance2.type); | |
// Static method | |
console.log(Singleton.staticMethod()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment