I. Definition
Guarantees that a class has only one instance and provides a global access point to access it.
When you click the login button, a landing floating window appears on the page, the Landing window is unique, no matter how many clicks the login button, the floating window will only be created once, then the landing window is suitable for the use of single case mode to create.
Ii. Principle of realization
To implement a singleton is not complicated, a variable is used to flag whether an object has already been created for a class, and if so, the object created earlier is returned directly the next time an instance of the class is obtained.
Third, the false single case
Global variables are not a single case pattern, but in JavaScript development we often use global variables as a single example.
Reduce the naming pollution caused by global variables
(1) using namespaces
var Namespace1 = {
a:function () {},
b:2
}
(2) using closures to encapsulate private variables
var user = (function () {
var _name = ' Lee ',
_age = ';
return {
getuserinfo:function () {return
_name + ":" + _age;}}
) ();
Iv. inert Singleton: To create an object instance when needed
var getsingle = function (fn) {
var result;
return function () {return result
| | (Result = Fn.apply (this, arguments));
};
Test
function TestSingle () {}
Getsingle (testsingle) () = = Getsingle (testsingle) (); True
V. Add:
(1) Lazy loading
var lazyload = function () {
console.log (1);
Lazyload = function () {
console.log (2);
}
return Lazyload ();
}
Lazyload ();
(2) Pre-loading
var preload = (function () {
console.log (1);
preload = function () {
console.log (2);
};
return preload;
}) ();
Preload ();
I hope this article will help you learn about JavaScript programming.