Created
April 16, 2016 17:41
-
-
Save dmnsgn/14d9f5d0c37870c83ba7e5d5b0653106 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: constructor return an instance scoped to the module
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
// http://amanvirk.me/singleton-classes-in-es6/ | |
let instance = null; | |
class SingletonModuleScopedInstance { | |
constructor() { | |
if (!instance) { | |
instance = this; | |
} | |
this._type = 'SingletonModuleScopedInstance'; | |
this.time = new Date(); | |
return instance; | |
} | |
singletonMethod() { | |
return 'singletonMethod'; | |
} | |
static staticMethod() { | |
return 'staticMethod'; | |
} | |
get type() { | |
return this._type; | |
} | |
set type(value) { | |
this._type = value; | |
} | |
} | |
export default SingletonModuleScopedInstance; | |
// ... | |
// index.js | |
import SingletonModuleScopedInstance from './SingletonModuleScopedInstance'; | |
// Instantiate | |
const instance2 = new SingletonModuleScopedInstance(); | |
console.log(instance2.type, instance2.singletonMethod()); | |
// Time test | |
console.log(instance2.time); | |
// Getter/Setter | |
instance2.type = 'type updated'; | |
console.log(instance2.type); | |
setTimeout(() => { | |
const instance2ReinstanciateAttempt = new SingletonModuleScopedInstance(); | |
console.log(instance2ReinstanciateAttempt.time); // Return the same time | |
}, 1000); | |
// Static method | |
console.log(SingletonModuleScopedInstance.staticMethod()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment