Monomer (Singleton) Pattern is one of the most basic and most commonly used patterns in Javascript. It is often used to divide namespaces and modularizeCodeAnd reduce global variables.
The following is the basic structure.
VaR Singleton = {<br/> attribute1: True, <br/> attribute2: 10, <br/> Method1: function () {<br/> }, <br/> method2: function (ARG) {<br/>}< br/>}; <br/> Singleton. attribute1 = false; <br/> var Total = Singleton. attribute2 + 5; <br/> var result = Singleton. method1 ();
It is worth learning about the monomer and the lazy loaded monomer with private members. The syntax is very simple, mainly to understand the programming ideas behind different methods.
In the past, the method that begins with an underscore is often used to indicate private, but this method can only be used as a specification and cannot be used to prevent others from malicious use. Using closures to create private members is a strict practice. In an anonymous function, private variables and methods are defined and single objects are returned, so that only methods in a single object can access private members.
Mynamespace. singleton = (function () {<br/> // Private Members. <br/> var privateattribute1 = false; <br/> var privateattribute2 = [1, 2, 3]; </P> <p> function privatemethod1 () {<br/>... <br/>}< br/> function privatemethod2 (ARGs) {<br/>... <br/>}< br/> return {// public members. <br/> publicattribute1: True, <br/> publicattribute2: 10, </P> <p> publicmethod1: function () {<br/>... <br/>}, <br/> publicmethod2: function (ARGs) {<br/>... <br/>}< br/>}; <br/> })();
The above two monomer types are created during Script Loading. for resource-intensive and configuration overhead (memory) large or unusable monomer, this technology is called lazy loading. Lazy loading is a little complicated, but it is also easy to understand, it is instantiated only once in the first call.
mynamespace. singleton = (function () {</P> <p> var uniqueinstance; // private attribute that holds the single instance. </P> <p> function Constructor () {// Single Code <br/>... <br/>}</P> <p> return {<br/> getinstance: function () {<br/> If (! Uniqueinstance) {// instantiate only if the instance doesn't exist. <br/> uniqueinstance = Constructor (); <br/>}< br/> return uniqueinstance; <br/>}< br/> }) (); <br/> // call method <br/> mynamespace. singleton. getinstance (). publicmethod1 ();