Solution 1: using the two functions of closures, You can flexibly read internal variables. Second, you can keep these variables in the memory.
Copy codeThe Code is as follows:
// Solution 1
Var SingletonTester = (function (){
// Singleton Method
Function Singleton (args ){
Var args = args || {};
This. name = 'singletontester'; // The external attribute of the method. The other method is to return the object.
This. pointX = args. pointX | 6;
This. pointY = args. pointY | 10;
}
// Singleton instance
Var instance;
// Return object
Return {
Name: 'singletontester ',
GetInstance: function (args ){
If (instance === undefined ){
Instance = new Singleton (args );
}
Return instance;
}
};
}) (); // Directly execute this method
// Test
Var test = SingletonTester. getInstance ({pointX: 5 });
Console. log (test. pointX );
Solution 2:
Copy codeThe Code is as follows:
// Solution 2
Function Universe (){
// Determine whether an instance exists
If (typeof Universe. instance === 'object '){
Return Universe. instance;
}
// Other content
This. start_time = 0;
This. bang = "Big ";
// Cache
Universe. instance = this;
// Implicitly return this
}
// Test
Var uni = new Universe ();
Var uni2 = new Universe ();
Console. log (uni === uni2); // true