Javascript utility function to convert a class - "constructor function" to singleton

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(); // returns the circle instance var circle2 = new Circle(); // throws Error "Already instantiated once, this is Singleton" 

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!

+4
source share
3 answers
 function Singleton(param){ var count = 0, old = window[param]; window[param] = function(){ if(++count <= 1) return old; else alert('NO WAY!'); } } 

You would call it like:

 Singleton('Circle'); 

Demo: http://jsfiddle.net/maniator/7ZFmE/

Remember that this only works if Circle or any other function class is in the global window namespace. Anything in any other namespace will require a few more manipulations to make it work completely.

+3
source

Try the following:

 Circle = function () { if (!(this instanceof Circle)) { // called as function return Circle.singleton || (Circle.singleton = new Circle()); } // called as constructor this.name = "the circle"; }; 

Now, without a new operator, you will get a singleton or a new one using

 var mycircle = Circle(); 

Remember that I use the global name for example, you can also do

 var Circle = window.Circle = function () { //... 
0
source

Of course, you can also create one instance of Object with the ability to use closures with something like:

 var singlecircle = (new function(name) { this.name = name || "Default circle";}('squared') ); singlecircle.name; //=> 'squared' 
0
source

Source: https://habr.com/ru/post/1444193/


All Articles