Home  >  Article  >  Web Front-end  >  JavaScript's singleton pattern (singleton in Javascript)_js object-oriented

JavaScript's singleton pattern (singleton in Javascript)_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:25:16993browse

The basic structure of the singleton pattern:

Copy code The code is as follows:

MyNamespace.Singleton = function () {
return {};
}();

For example:
Copy code The code is as follows:

MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})( );

However, the above Singleton has been created as soon as the code is loaded. How to delay loading? Imagine how to implement a singleton in C#:) Use the following pattern:
Copy the code The code is as follows:

MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();

Specifically, create a singleton Put the code in the constructor and instantiate it when it is called for the first time:
The complete code is as follows:
Copy the code Code As follows:

MyNamespace.Singleton = (function() {
var uniqueInstance; // Private attribute that holds the single instance.
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
if(!uniqueInstance) { // Instantiate only if the instance doesn't exist.
uniqueInstance = constructor();
}
return uniqueInstance;
}
}
})();
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