Singleton pattern: Ensure that there is only one instance of a class and provide a global access point to access it: Assume that when we click the login button, a login hover box appears on the page. This login box is unique and will only be created once no matter how many times the login button is clicked. A variable is used to indicate whether an object has been created for a class. If so, the next time an instance of the class is retrieved, the object is returned
Normal singleton mode
var singleton = function(name){ his.name = name } singleton.instance = null singleton.prototype.getName = function(){ alert(this.name) } singleton.getInstance = function(name){ if(! this.instance){ this.instance = new singleton(name) } return this.instance } var a = singleton.getInstance('seven1') var b = singleton.getInstance('seven2') console.log(a===b) // trueCopy the code
Implement the singleton pattern with a proxy
var proxySingletonCreateDiv = (function(){ var instance return function(html){ if(! instance){ instance = new createDiv(html) } return instance } })() var a1 = new proxySingletonCreateDiv('seven1') var b1 = new proxySingletonCreateDiv('seven2') console.log(a1===b1) //trueCopy the code
Lazy singleton pattern
var createLoginLayer = (function(){ var div; return function(){ if(! Div){// global! Div = document.createElement('div'); Div. InnerHTML = 'I am a login shell'; div.style.display = 'none'; document.body.appendChild(div); } return div; }}) (); document.getElementById('loginBtn').onclick=function(){ var loginLayer = createLoginLayer(); loginLayer.style.display = 'block' }Copy the code
Generic lazy singleton pattern: Pass fn as a closure
var getSingle = function(fn){ var result; / / use the result to save the result of fn, because the result in the closure, it will never be destroyed the return function () {return result | | (result = fn. Apply (this, the arguments)); } } var createLoginLayer = function(){ var div = document.createElement('div'); Div. InnerHTML = 'I am a login shell'; div.style.display = 'none'; document.body.appendChild(div); return div; } var createSingleLoginLayer = getSingle(createLoginLayer); document.getElementById('loginBtn').onclick=function(){ var loginLayer = createSingleLoginLayer(); loginLayer.style.display = 'block' }Copy the code
Summary: The core of the singleton pattern is to ensure that there is only one instance and provide global access. The var global variable is not a singleton pattern, but can be used as a singleton in JavaScript development. Closure (function inside a function) : A function that can read local variables inside a function. The values of these variables are always kept in memory. After the function is executed, the scope of the function execution is destroyed, but the active object is not destroyed.