The idea is to ensure that a class corresponds to only one instance.
1. Use closures
function Base() {}
Base.prototype.test = 1;
const single = (function () {
let instance = null;
return function () {
if(! instance) { instance = new Base() }return instance
}})()
const a = single();
const b = single()
console.log(a === b)
a.test = 2;
console.log(b.test)Copy the code
2. Use the static properties of the ES6 class
class Base {
static getInstace() {
if(! Base.instance) { Base.instance = new Base() }return Base.instance }
}
const a = Base.getInstace();
const b = Base.getInstace()
console.log(a === b)
a.test = 2;
console.log(b.test)Copy the code
3. Actually apply the modal box to create a singleton pattern in the constructor
<! DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="Width = device - width, initial - scale = 1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head><body> <button id='a'>opne</button> <button id='b'>close</button> <script> class Modol { constructor() { if(! Modol.instace) { Modol.instace = this } this.div = document.createElement('div'); this.div.innerHTML = ' ' document.querySelector('body').append(this.div) return Modol.instace; } open() { this.div.innerHTML = 'open' } close() { this.div.innerHTML = 'close' } } document.querySelector('#a').addEventListener('click', () => { const modol = new Modol(); modol.open() }) document.querySelector('#b').addEventListener('click', () => { const modol = new Modol(); modol.close() }) </script></body></html>Copy the code