JavaScript - singleton

  • The system is unique in the use
  • Only one instance of a class

Reference: https://www.cnblogs.com/zjoch/p/4455530.html

 1 // 单列模式
 2   class SingleObject {
 3     login() {
 4       console.log('login...')
 5     }
 6   }
 7   SingleObject.getInstance = (function () {
 8     let instance
 9     return function () {
10       if (!instance) {
11         instance = new SingleObject()
12       }
13       return instance
14     }
15   })()
16 
17 let obj1 = SingleObject.getInstance() 18 obj1.login() 19 let obj2 = SingleObject.getInstance() 20 obj2.login() 21 22 console.log('obj1 === obj2', obj1 === obj2) // true

Guess you like

Origin www.cnblogs.com/PasserByOne/p/12163589.html