Javascript Singleton mode and javascript Mode
Classic applications in singleton mode:
For example, applications such as the job manager and recycle bin in the window always maintain only one instance. For example, website counters are synchronized using the singleton mode.
Javascript Singleton mode:
1. Lazy, that is, the object is created only when the object instance needs to be created.
<Script type = "text/javascript"> var Singleton = (function (window) {var instance = null; // The Task Manager // puts it in the Self-executed function, avoid creating the function TaskManager () {this. count = 0;} // provides it to the external interface to obtain the function getInstance () {if (instance = null) {instance = new TaskManager ();} return instance;} // Extension Method TaskManager. prototype = {constructor: TaskManager, size: function () {this. count ++; return this. count ;}; return {getInstance: getInstance };} (window); var instance = Singleton. getInstance (); alert (instance. size (); // 1var instance2 = Singleton. getInstance (); alert (instance2.size (); // 2 </script>In the code, get the TaskManager instance object through Singleton. getInstance (); and the TaskManager object is created only once, and the instance object is shared.
So instance2.size () will print 2.
In this case, instance1 = instance2.
2. The implementation of the hungry Chinese Singleton mode will first initialize the instance object, pay attention to the instance initialization location.
<Script type = "text/javascript"> var Singleton = (function (window) {var instance; function TaskManager () {this. count = 0;} // provides it to the external interface to obtain the function getInstance () {return instance;} // Extension Method TaskManager. prototype = {constructor: TaskManager, size: function () {this. count ++; return this. count ;}}; // instance initialization instance = new TaskManager (); return {getInstance: getInstance };}) (window); var instance = Singleton. getInstance (); alert (instance. size (); var instance2 = Singleton. getInstance (); alert (instance2.size (); </script>If the first step is var instance = new TaskManager (), the size () method is added because TaskManager overwrites the prototype method. the TaskManager instance object obtained by getInstance () does not have the size method, and an instance is thrown. an error occurred while defining the size () method.