A truly global, isomorphoic, extendable JavaScript singleton class.
Install the package:
npm i @cocopina/singleton
You can then extend your class to implement the Singleton
class:
import Singleton from '@cocopina/singleton';
class MyClass extends Singleton {}
const a = MyClass.getInstance();
const b = MyClass.getInstance();
console.log(a === b); // true
You can alternatively use the asSingleton
decorator like so:
import { asSingleton } from '@cocopina/singleton';
class MyClass {}
const MySingletonClass = asSingleton(MyClass);
const a = MySingletonClass.getInstance();
const b = MySingletonClass.getInstance();
console.log(a === b); // true
Gets the singleton's instance.
If none exists, will create a new one and store it on the global scope.
Gets the singleton's instance, an alias for getInstance()
.
Clears the singleton's instance from the global scope.