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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:25:16
Original
1062 people have browsed it

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;
}
}
})();
Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template