单例模式--登陆框

 1 // 例2 === 模拟登陆框
 2   class LoginForm {
 3     constructor() {
 4       this.state = 'hide' // 存储当前显示,隐藏状态
 5     }
 6     show() {
 7       if (this.state === 'show') {
 8         alert('已经显示')
 9         return
10       }
11       this.state = 'show'
12       console.log('登陆框显示')
13     }
14     hide() {
15       if (this.state === 'hide') {
16         alert('已经隐藏')
17         return
18       }
19       this.state = 'hide'
20       console.log('登陆框已隐藏')
21     }
22   }
23   // 单例模式开启=>
24   LoginForm.getInstance = (function() {
25     let instance  // 寄存new出来的LoginForm实例 确保唯一性
26     return function() {
27       if (!instance) {  // 判断instance是否有值
28         instance = new LoginForm()
29       }
30       return instance
31     }
32   })()
33 
34   window.p1 = LoginForm.getInstance()

猜你喜欢

转载自www.cnblogs.com/PasserByOne/p/12165327.html
今日推荐