I have some information about two ways to create a singleton in javascript - simple object literature, and the other - the closure method, if we want to use private variables.
I want to create a utility function like
Singleton(classname);
Regardless of the class - the "design function", which I pass here as an argument, the Singleton method converts this class to a Singleton, PLUS object after calling new Classname() , if someone starts the new class name () again, it gets a few new Error ( "Already instantiated once, this is Singleton" );
Usage example - below -
function Circle() {this.name = "Circle";} SingleTon(Circle); var circle1 = new Circle();
I'm just trying to define the "Singleton" method here.
I saw a similar example where the getInstance method is used to get an instance of type Singleton.getInstance (Circle), etc., but I am looking for a specific question above where another programmer, accustomed to creating an instance in the "new" way, is trying to start new Circle(); a second time in its code and receives an error message.
Creating a singleton this way is one of the problems, but the main problem is that you throw out an βErrorβ, for which, as far as I know, the Circle constructor needs to be modified somewhere in the Singleton function, not sure how to do it.
Is there any solution?
Thanks in advance!
source share