Skip to content

Instantly share code, notes, and snippets.

@Gladozzz
Last active January 13, 2021 17:34
Show Gist options
  • Save Gladozzz/ab8a208dd2519d3441aa960d7bfa1d03 to your computer and use it in GitHub Desktop.
Save Gladozzz/ab8a208dd2519d3441aa960d7bfa1d03 to your computer and use it in GitHub Desktop.
javascript singleton class
// const Singleton = (function() {
// var _instance;
// function init() {
// var privateProperty = "private " + Math.floor(Math.random() * 100);
// function privateMethod() {
// console.log(privateProperty);
// }
// return {
// publicProperty: "public " + Math.floor(Math.random() * 100),
// publicMethod: function() {
// console.log("public");
// privateMethod();
// }
// }
// }
// return {
// getInstance: function() {
// if ( !_instance ) {
// _instance = init()
// }
// return _instance;
// }
// }
// })();
class Singleton {
static #instance;
publicProperty = "public " + Math.floor(Math.random() * 100);
#privateProperty = "private " + Math.floor(Math.random() * 100);
constructor() {
if (Singleton.#instance != null) {
return Singleton.#instance;
}
Singleton.#instance = this;
}
#privateMethod = function () {
console.log(this.#privateProperty);
}
publicMethod() {
console.log("public");
this.#privateMethod();
}
static getInstance() {
if (Singleton.#instance != null) {
return Singleton.#instance;
}
return Singleton.#instance = new Singleton();
}
}
var sing = Singleton.getInstance();
sing.publicMethod();
// var sing1 = Singleton.getInstance();
var sing1 = new Singleton();
sing1.publicMethod();
if (sing.publicProperty === sing1.publicProperty) {
console.log(true);
} else {
console.log(false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment