const singleton = (function () { let instance; //创建函数也可以写在外面 function User(name, age) { this.name = name this.age = age } return function (name, age) { if (!instance) instance = new User(name, age) return instance } })()
singleton('gl', 30) singleton('gz', 40)
class Singleton { constructor(name, age) { if (!Singleton.instance) { this.name = name this.age = age Singleton.instance = this } return Singleton.instance; } }
console.log(new Singleton('gl', 30) == new Singleton('gz', 40));
let Modal = (() => { let instance = null return () => { if (!instance) { instance = document.createElement('div') instance.innerHTML = 'Box' instance.style.display = 'none' document.body.appendChild(instance) } return instance } })() let open = document.querySelector('#open') open.addEventListener('click', () => { let singleton = Modal() singleton.style.display = 'block' }) let close = document.querySelector('#close') close.addEventListener('click', () => { let singleton = Modal() singleton.style.display = 'none' })