1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
class Dialog { constructor() { this.dislogDom = document.createElement('div') this.isShow = false this.content = '' } handleShow(content) { this.content = content this.dislogDom.innerText = this.content if (this.isShow) return this.isShow = true document.body.appendChild(this.dislogDom) } handleClose() { if(!this.isShow) return this.isShow = false document.body.removeChild(this.dislogDom) } }
Dialog.getInstance = (function() { let instance return function() { if(!instance) { instance = new Dialog() } return instance } })()
const myDialog1 = Dialog.getInstance() myDialog1.handleShow('1111') setTimeout(() => { const myDialog2 = Dialog.getInstance() myDialog1.handleShow('222') console.log(myDialog1 === myDialog2) }, 2000);
const proxyDialog = (function() { let ins return function() { return ins || (ins = new Dialog()) } })()
const d1 = new proxyDialog() const d2 = new proxyDialog()
const getInstance = function(fn) { let ins return () => { return ins || (ins = fn.call({}, arguments)) } }
const Dialog = function () { this.dislogDom = document.createElement('div') this.isShow = false this.content = '' this.handleShow = (content) => { this.content = content this.dislogDom.innerText = this.content if (this.isShow) return this.isShow = true document.body.appendChild(this.dislogDom) } this.handleClose = () => { if(!this.isShow) return this.isShow = false document.body.removeChild(this.dislogDom) } return this }
const cd = getInstance(Dialog) const cdOther = getInstance(Other) const d1 = cd() const d2 = cd() console.log(d1 === d2)
|