The single object is created when the script is loaded. The following code:
Var Singleton = (function () {// common standalone Mode
// Code here
Return {
};
})();
For resource-intensive or configuration-intensive monomer, it may be more reasonable to postpone its instantiation until it needs to be used. This technology is called "lazyloading", which is most commonly used for the units that must load a large amount of data. It is better to instantiate the tool that is used as a namespace, a specific code package for a specific webpage, or a practical method for organizing the relevant methods.
The special feature of this kind of inert loading monomer is that access to them must rely on a static method. The method Singleton. getInstance (). methodName () should be called like this instead of Singleton. methodName (). The getInstance method checks whether the monomer has been instantiated. If not, it creates and returns its instance. If the monomer has been instantiated, it returns the existing instance.
Compare the common monomer mode with the inert loaded monomer mode:
Var Singleton = (function () {// standalone mode for inert Loading
Var uniqueInstance = null;
Function constructor (){
// Code here
Return {
};
}
Return {
GetInstance: function (){
If (! UniqueInstance ){
UniqueInstance = constructor ();
}
Return uniqueInstance;
}
};
})();