The basic structure of singletoninJavascript Singleton mode:
The Code is as follows:
MyNamespace. Singleton = function (){
Return {};
}();
For example:
The Code is as follows:
MyNamespace. Singleton = (function (){
Return {// Public members.
PublicAttribute1: true,
PublicAttribute2: 10,
PublicMethod1: function (){
...
},
PublicMethod2: function (args ){
...
}
};
})();
However, the Singleton above has been established when the code is loaded. How can we delay loading? Imagine how to implement Singleton in C #: Use the following mode:
The Code is as follows:
MyNamespace. Singleton = (function (){
Function constructor () {// All of the normal singleton code goes here.
...
}
Return {
GetInstance: function (){
// Control code goes here.
}
}
})();
Specifically, put the code for creating a singleton In the constructor and instantiate the code at the first call:
The complete code is as follows:
The Code is as follows:
MyNamespace. Singleton = (function (){
Var uniqueInstance; // Private attribute that holds the single instance.
Function constructor () {// All of the normal singleton code goes here.
...
}
Return {
GetInstance: function (){
If (! UniqueInstance) {// Instantiate only if the instance doesn't exist.
UniqueInstance = constructor ();
}
Return uniqueInstance;
}
}
})();