In object-oriented languages such as C # and Java, the rational use of the design pattern will make our module design and Code Write more robust and clear. Currently, JavaScript has been compiled from its own object-based language, which has been gradually simulated as (at least points) the object-oriented language, therefore, we can follow some design patterns to write JS Code.
Singleton is the simplest mode in the design mode, so let's take it first. For more information about Singleton, see Implementing the Singleton pattern in C #. If you want to understand the system, it belongs to the scope of the design model.
However, for C #, Java and other pure object-oriented languages, constructor is not a common function (and its return value cannot be customized ), therefore, when writing a singleton class, they all need to use a static property or method to obtain the instance of the object. In JavaScript, constructor is a common function. We can change its return value to realize the return of an object instance without relying on the language mechanism. What does this mean? Let's take a look at the implementation of the JS Singleton class. The sample code is as follows:
< Script Language = "JavaScript" >
Function Singleton ()
{
// Template code for Singleton class.
If ( This . Constructor. instance)
{
Return This. Constructor. instance;
}
Else This . Constructor. Instance = This ;
/**/ /**/ // ///////////////////////////////
This . Value = Parseint (math. Random () * 1000000 );
This . Tostring = Function ()
{
Return'[Class Singleton]';
}
}
Singleton. Prototype. getvalue = Function ()
{
Return This. Value;
} ;
Singleton. Prototype. setvalue = Function (Value)
{
This. Value=Value;
} ;
</ Script >
As mentioned above, "changing its return value to realize the return of an object instance" means that the constructor class in the Javascript class canReturn this. Constructor. instance ;. Therefore, the singleton class implemented by javascript can only be used with the new class, instead of the classname. instance or classname. getinstance () syntax.
The test code for Singleton is as follows:
VaR Singleton = New Singleton ();
Alert (_ typeof _ (Singleton ));
Alert (singleton. getvalue ());
VaR Singleton = New Singleton ();
Alert (singleton. getvalue ());
Singleton. setvalue ( 1000000 );
VaR Singleton = New Singleton ();
Alert (singleton. getvalue ());
VaR Singleton = New Singleton ();
Alert (singleton. getvalue ());
Return results: Singleton, 586606, 586606, 000000,000000. The second and third are random, and they must be the same two numbers (the implementation of _ typeof _ comes from here: Get the Class Name of the Javascript user-defined class ).