Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Created February 15, 2025 11:30
Show Gist options
  • Save atomjoy/87f693b656620395942d3e30797a7fc7 to your computer and use it in GitHub Desktop.
Save atomjoy/87f693b656620395942d3e30797a7fc7 to your computer and use it in GitHub Desktop.
Js singleton
// First example
export default class Singleton {
number = 0;
constructor() {
if (!!Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
// return this;
}
setCounter(number) {
this.number = number;
}
}
// Second example
// let instance;
// export default class Singleton {
// constructor() {
// if (instance) {
// return instance;
// // throw new Error('You can only create one instance!');
// }
// instance = this;
// }
// setCounter(number) {
// this.number = number;
// }
// }
// let notEditable = Object.freeze(new Singleton());
// let instanceOne = new Singleton();
// let instanceTwo = new Singleton();
// instanceTwo.setCounter(5);
// instanceTwo.setCounter(6);
// console.log('Singleton:', instanceOne, instanceTwo); // Logs "true"
// console.log('Singleton:', instanceOne === instanceTwo); // Logs "true"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment