單例模式在js中的寫(xiě)法,十分簡(jiǎn)單职车,話不多說(shuō),上代碼:
let Store = function (name) {
this.name = name
}
Store.prototype.getName = function () {
return this.name
}
Store.getInstance = (function () {
let instance = null
return function (name) {
if (!instance) {
instance = new Store(name)
}
return instance
}
})()
let store = Store.getInstance('car')
let store2 = Store.getInstance('car2')
console.log(store, store2, store === store2)
透明單例
let Store = (function () {
let instance = null
let Store = function (name) {
if (instance) {
return instance
} else {
this.name = name
instance = this
return instance
}
}
Store.prototype.getName = function () {
return this.name
}
return Store
})()
let store1 = new Store('car')
let store2 = new Store('car2')
console.log(store1, store2, store1 === store2)
應(yīng)用:
- 模態(tài)對(duì)話框
- 方法與組件庫(kù)