let singleObj = {
name:'loser',
age:18,
getAge:function(){
return this.age;
}
}
function Singleton(name){
this.name = name
}
Singleton.getInstance = function(name){
if(!this.instance){
this.instance = new Singleton()
}
return this.instance;
}
var a = Singleton.getInstance('a')
var b = Singleton.getInstance('b')
//例子2
var mySingleton=(function(){
//构造器函数
function singleton(options){
options=options || {}
this.name='SingletonTestor';
this.pointX=options.pointX || 6
this.pointY=options.pointY || 10;
}
function init(){
let now=new Date() //私有方法
this.name='公共的属性'
this.getISODate()=function(){
return now.toISOString();
}
}
//缓存单例的变量
var instance;
var _static={
name:'SingletonTestor',
getInstance:function(options){
if(!instance){
instance=new singleton(options)
}
return instance
}
}
return _static
})()
var singletonTest=mySingleton.getInstance({
pointX:5,
pointY:5
})
console.log(singletonTest)
var singletonTest1=mySingleton.getInstance({
pointX:10,
pointY:10
})
class Single{
constructor(name){
this.name = name;
this.instance = null;
}
static getInstance(name){
if(!this.instance){
this.instance = new Single(name);
}
return this.instance;
}
}
console.log(Single.getInstance('test'))
let test2=Single.getInstance('test2')
console.log(d)
function StorageBase(){
StorageBase.prototype.getItem=function(){
return localStorage.getItem(key)
}
StorageBase.prototype.setItem=function(){
return localStorage.setItem(key,value)
}
}
const Storage1=(function(){
let instance=null
return function (){
if(!instance){
instance=new StorageBase()
}
return instance
}
})()
const storage3=new Storage1()
console.log(storage3)
const storage2=new Storage1()
storage3.setItem('name','张三')
storage3.getItem('name') //张三
storage2.getItem('name')//张三
function store(){
if(store.instance){
return store.instance
}
store.instance=this
}
//同
function store(){
if(!(this instanceof store)){
return new store()
}
}
上面得代码 可以new 也可以直接使用 ,这里使用了一个静态变量instance来记录是否有进行过实例化,如果实例化了就返回这个实例,如果没有实例化说明使第一次调用,就会把this赋给这个静态变量,因为是使用new 调用,这时候得this指向得就是实例化出来得对象,并且最后会隐式得返回this
var a=new store()
var b=store()
a==b