单例模式在js中的写法,十分简单,话不多说,上代码:
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)
应用:
- 模态对话框
- 方法与组件库
网友评论