Single-chat mode is a very extreme pattern that guarantees that a class has only one entity in the entire application domain, which means that when you create instances of a class multiple times, they are the first ones created.
In a Java or C # environment, it is simple to implement a singleton pattern, just define a static variable, save the object in a static variable, and the static variable does not change with the class instance. Similarly, JavaScript is a similar implementation principle.
Common static variables for single-instance mode
var Earth = (function () { if (typeof earth.instance = = = ' object ') { C8>return earth.instance; } this. Name = "Earth"; this. Age = $ * * + * 10000; This ; return earth.instance;});
The earth.instance in the code is a public static variable, and the public static variable is invisible in the instantiated object earth1
But it can be seen in the Earth class.
var New Earth (); var New = = = Earth2);
Because it is a singleton mode, the result is obviously ' true '
Private static variables for single-instance mode
Storing an instance in a public variable is simple, but there is a fatal problem that the public variable can be changed externally, so the best way to use private static variables is to use a private static variable that needs to be implemented by a timely function and a closure.
varEarth = (function () { varinstance; return function () { if(typeofInstance = = = ' object ') { returninstance; } This. Name = "Earth"; This. Age = 46 * 1000 * 1000 * 10000; Instance= This; returninstance; }}());
The entire function returns a closure function and executes immediately, in a timely manner: (function () {} ())
Execute again
var New Earth (); var New = = = Earth2);
The results are still ' true '
Summarize:
Singleton mode is very extreme mode, can be implemented by static variable storage instances, through the implementation of private static need to rely on timely functions and closures, on-time functions and closures are no longer cumbersome here.
JavaScript mode (2)--Singleton mode