Last active
December 15, 2018 05:23
-
-
Save VincentDebug/5e303dd7ae350964ad42735e848d6c37 to your computer and use it in GitHub Desktop.
Creating A True Singleton In Node.js, With ES6 Symbols
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
// https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/ | |
// create a unique, global symbol name | |
// ----------------------------------- | |
const FOO_KEY = Symbol.for("My.App.Namespace.foo"); | |
// check if the global object has this symbol | |
// add it if it does not have the symbol, yet | |
// ------------------------------------------ | |
var globalSymbols = Object.getOwnPropertySymbols(global); | |
var hasFoo = (globalSymbols.indexOf(FOO_KEY) > -1); | |
if (!hasFoo){ | |
global[FOO_KEY] = { | |
foo: "bar" | |
}; | |
} | |
// define the singleton API | |
// ------------------------ | |
var singleton = {}; | |
Object.defineProperty(singleton, "instance", { | |
get: function(){ | |
return global[FOO_KEY]; | |
} | |
}); | |
// ensure the API is never changed | |
// ------------------------------- | |
Object.freeze(singleton); | |
// export the singleton API only | |
// ----------------------------- | |
module.exports = 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
class SingletonDefaultExportInstance { | |
constructor() { | |
this._type = 'SingletonDefaultExportInstance'; | |
} | |
singletonMethod() { | |
return 'singletonMethod'; | |
} | |
static staticMethod() { | |
return 'staticMethod'; | |
} | |
get type() { | |
return this._type; | |
} | |
set type(value) { | |
this._type = value; | |
} | |
} | |
export default new SingletonDefaultExportInstance(); | |
// ... | |
// index.js | |
import SingletonDefaultExportInstance from './SingletonDefaultExportInstance'; | |
// Instantiate | |
// console.log(new SingletonDefaultExportInstance); // is not a constructor | |
// Prototype Method | |
console.log(SingletonDefaultExportInstance.type, SingletonDefaultExportInstance.singletonMethod()); | |
// Getter/Setter | |
SingletonDefaultExportInstance.type = 'type updated'; | |
console.log(SingletonDefaultExportInstance.type); | |
// Static method | |
console.log(SingletonDefaultExportInstance.constructor.staticMethod()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment