What is a singleton?
A singleton requires a class to have one and only one instance, providing a global access point. Therefore, it has to bypass the regular controller so that it can only have one instance for the user to use, and the user does not care about how many instances there are, so this is the designer's responsibility
In JavaScript, a singleton is treated as a global namespace, providing a point of access to the object.
Usage scenarios
A single case is somewhat similar to the team leader of a group. There is only one team leader for a period of time, and the team leader designates the work of the team members, assigns and coordinates the work of the team members.
Example 1: This is the simplest singleton, which stores attributes and methods in the form of key and value
function init() {
//Private methods and variables
function privateMethod(){
console.log( "I am private" );}
var privateVariable = "Im also private";
// Shared methods and variables
publicMethod: function () {
console.log( "The public can see me!" ); },
publicProperty: "I am also public"
};
};
// If the instance does not exist, create one
getInstance: function () {
if ( !instance ) {
instance = init();
return instance;
}
};
var singleA = mySingleton;
var singleB = mySingleton;
console.log( singleA === singleB ); // true