Skip to content

Instantly share code, notes, and snippets.

@mcharytoniuk
Created April 2, 2019 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcharytoniuk/c6779435ae53cfb1a7eeab38a8eefebd to your computer and use it in GitHub Desktop.
Save mcharytoniuk/c6779435ae53cfb1a7eeab38a8eefebd to your computer and use it in GitHub Desktop.
// 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