静态属性中的实例
function Universe(){
// 判断是否有现有的实例(是否缓存过实例)
if(typeof Universe.instance === "object"){
return Universe.instance;
}
this.start_time = 0;
this.bang = 'Big';
// 缓存实例
Universe.instance = this;
// 隐式返回
// return this;
}
var uni = new Universe();
var uni2 = new Universe();
alert(uni === uni2);
缺点是instance属性是公开的,可能会被修改
闭包中的实例
function Universe(){
// 缓存实例
var instance = this;
// 重写构造函数
Universe = function(){
return instance;
}
// 修正操作:防止重写构造函数丢失所有在初始定义和重定义时刻添加的属性
// 保留原型属性
Universe.prototype = this;
// 实例
instance = new Universe();
// 重置构造函数指针
instance.constructor = Universe;
this.start_time = 0;
this.bang = "Big";
return instance;
}
还有一种修正方式是把构造函数和实例包装在即时函数中。在第一次调用构造函数时会创建一个对象,并且使私有instance指向该对象,第二次调用时仅会返回该对象。
var Universe;
(function(){
var instance;
Universe = function Universe(){
if(instance){
return instance;
}
instance = this;
this.start_time = 0;
this.bang = "Big";
}
}())