weijiyang / GOOD-IDEA

这里记录一些灵感~详见ISSUES
1 stars 0 forks source link

js 实现单例模式? #36

Open weijiyang opened 4 years ago

weijiyang commented 4 years ago

首先需要搞懂单例模式 就是一个构造函数只能生成一个实例

var Single = (function () {
   let instance = null
  let Single = function (name) {
     this.name = name
  }
 return function (name) {
   if(!instance) instance = new Single(name)
   return instance
 }
})()

var a = new Single('namea')
var b = new Single('nameb')
console.log(a === b)
weijiyang commented 4 years ago
class Single {
  constructor (name) {
    this.instance = null
    this.name = name
 }
static foo (name) {
 if(!this.instance) this.instance = new Single(name)
 return this.instance
} 
}

var a = Single.foo('name1')
var b = Single.foo('name2')
console.log(a === b)