var instance;
function singleton(){
if (instance != null){
return instance
}
this.name = 'Jim';
this.age = 10;
instance = this;
}
var a = new singleton();
var b = new singleton();
console.log(a === b);
上面这种方法可以实现单例模式,但是instance变成了全局属性,稍加改进,通过匿名函数形成闭包解决这个问题。
var singleton;
!function() {
var instance;
singleton = function() {
if (instance != null) {
return instance
}
this.name = 'Jim';
this.age = 10;
instance = this;
}
}()
var a = new singleton();
var b = new singleton();
console.log(a === b);