Home  >  Article  >  Web Front-end  >  Detailed Example of JS Singleton Pattern_Basic Knowledge

Detailed Example of JS Singleton Pattern_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 17:13:221363browse

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

Copy code The code is as follows:

In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

In JavaScript, a singleton is treated as a global namespace, providing a point of access to the object.

Usage scenarios

Copy code The code is as follows:

In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system.

Analogy

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

Copy code The code is as follows:var A = {
xx:3,
yy:4,
B:function(el){

},
C:function(el){

},
D:function(el ){

},
E:function(el){

}
}



Example 2: First create a reference to an instance, and then determine whether the instance exists. If it does not exist, create it. If it exists, return it directly, ensuring that there is and only one instance.


Copy code The code is as follows:var mySingleton = (function () {
//Instance stores a reference to a singleton instance
var instance;

function init() {

// Singleton

//Private methods and variables

function privateMethod(){

console.log( "I am private" );

}

var privateVariable = "Im also private";

return {

// Shared methods and variables

publicMethod: function () {

console.log( "The public can see me!" );

},

publicProperty: "I am also public"
};

};

return {

// 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




Example 3:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn