Skip to content

Instantly share code, notes, and snippets.


mcharytoniuk/singleton.js Secret

Created Apr 2, 2019
What would you like to do?
// Hello.js
// this one creates a new object, `priv` holds a unique reference that is not
// exported outside this file
// this is a really important variable, it needs to be privately scoped, it
// will be used to check if constructor is actually called properly
const priv = {};
export default class Hello {
static getInstance() {
return instance;
constructor(privCheck) {
// it's not possible to call this constructor outside this module, because
// 'priv' variable is not exported
if (privCheck !== priv) {
throw new Error("Hello is a singleton. Please use `getInstance` method instead");
getGreeting() {
return "Hello, world!";
const instance = new Hello(priv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment