# Singleton mode - front end design mode

2022-04-29 04:52:27

First, simply understand the word single example

single ： It's a single
example ： Is the instance , Since it is an example, it must be the same as new About the process of
stay new We all generate a Empty objects , Open up a space , If a constructor is new Many times
Is that to open up multiple spaces , Generate multiple objects .
Singleton mode is the solution to this problem , Only one object is generated to solve this problem

The following code reflects every time new Will generate different instances , Different objects

 		function Fn() {

}
let a1 = new Fn()
let a2 = new Fn()
console.log(a1 == a2); // fasle


What we want to achieve is How to let a1 == a2 yes true ?
Is there a possibility of a second new When It's the same space as the one used at the same time ！

Let's change the code
Analyze why true
a1 for the first time new When _instance = null
this Point to the yes a1
Overall _instance = this

The second time new When because _instance It's not equal to null Straight back this It means pointing. a1 Of this
therefore yes true

		let _instance = null
function Fn() {

if(!_instance) {

_instance = this
}
return _instance

}
let a1 = new Fn()
let a2 = new Fn()
console.log(a1 == a2); // true


Finally, optimize the code
Closures are used to prevent contamination of global variables
This Of self executing functions window It can not be passed , If it doesn't pass , Will destroy performance
because I'll find it layer by layer window.Fn

 		(function(window) {

let _instance = null
function Fn() {

if(!_instance) {

_instance = this
}
return _instance

}
window.Fn = Fn
})(window)

let g1 = new Fn()
let g2 = new Fn()
console.log(g1 == g2); // true