This article mainly introduces the singleton mode in the JavaScript design mode. If you are interested in the JavaScript design mode, refer to it.
I. Definition
Ensure that a class has only one instance and provides a global access point to it.
When you click the login button, a login floating window appears on the page, which is unique. No matter how many login buttons are clicked, this floating window will only be created once, this login floating window is suitable for creating in singleton mode.
II. Implementation Principle
It is not complex to implement a singleton. A variable is used to indicate whether an object has been created for a class. If yes, the next time you obtain the instance of this class, directly return the previously created object.
3. Case Study
Global variables are not in singleton mode, but we often use global variables as Singleton in JavaScript development.
var a = {};
Reduce naming pollution caused by global variables
(1) Use namespace
var namespace1 = { a: function(){}, b: 2}
(2) Use closures to encapsulate private variables
var user = (function() { var _name = 'lee', _age = '25'; return { getUserInfo: function() { return _name + ":" + _age; } };})();
4. inert singleton: object instances can be created only 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
5. Supplement:
(1) lazy loading
var lazyload = function() { console.log(1); lazyload = function() { console.log(2); } return lazyload();}lazyload();
(2) pre-load
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.