Nice Singleton Template in JavaScript

I use the following Singleton pattern in JavaScript:

var exampleClass =(function(){ //private var a ="test"; function PrivateMethod() { return a; } //public return{ Test: function() { alert(PrivateMethod()); } } })(); 

When I read StackOverflow, I see many other Singleton implementations, and I begin to doubt if I can improve my work. Hopefully someone can tell me what is right or wrong to do it this way.

+4
source share
5 answers

It depends on what you want to achieve, as different implementations will have different advantages and limitations.

The simplest implementation is just an object literal:

 var singleton = { property: "foo", method: function() { alert('bar'); } } 

The implementation you mentioned in the question allows public and private methods by encapsulating methods in closure and returning what needs to be revealed.

Here is an alternative that would similarly allow public and private methods and would be more extensible:

 function MySingletonClass() { if ( arguments.callee._singletonInstance ) return arguments.callee._singletonInstance; arguments.callee._singletonInstance = this; this.Foo = function() { // ... } } var a = new MySingletonClass() var b = MySingletonClass() Print( a === b ); // prints: true 
+3
source

It's mine.

Differences:

  • all functions declared above
  • all functions are private by default
  • all functions have access to other functions
  • public functions are displayed below

Enhancements:

  • If you want to move the function from private to public or vice versa, you do not need to move the code, but only change the display at the bottom of the code.
  • all functions have access to both private and public functions (since all functions are private by default)

     var exampleClass =(function(){ //private var a ="test"; //declare here all functions //(both for pass jslint validation and is good to have a list //of all available functions, in case of classes with a lot of code var PrivateMethod, Test1, Test2; PrivateMethod = function() { return a; }; Test1 = function() { return PrivateMethod(); }; Test2 = function() { return Test1(); }; //public //Expose function you want to have pubblic return{ Test1: Test1, Test2: Test2 } })(); 
+1
source

I am using this template:

 var SingletonConstructor; (function() { var instance; SingletonConstructor = function() { if (typeof instance !== 'undefined') return instance; var a = "a"; function PrivateMethod() { return a; } return instance = this; }; })(); 
0
source

I like the following pattern:

 function MyClass(){ if(MyClass.instance){ return MyClass.instance; } MyClass.instance = this; //constructor code goes here } var a = new MyClass(); var b = new MyClass(); console.log(a == b); //true 
0
source

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


All Articles