Created
February 15, 2025 11:30
-
-
Save atomjoy/87f693b656620395942d3e30797a7fc7 to your computer and use it in GitHub Desktop.
Js singleton
This file contains hidden or 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
// 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