1. 使用静态属性
<pre name="code" class="javascript">function Universe() {
if(typeof Universe.instance === "object") {
return Universe.instance;
}
this.start_time = 0;
this.bang = "big";
Universe.instance = this;
}
缺点:Universe.instance是公开的
2. 使用闭包
function <span style="font-family: Arial, Helvetica, sans-serif;">Universe</span><span style="font-family: Arial, Helvetica, sans-serif;">() {</span>
var instance = this;
this.start_time = 0;
this.bang = "big";
Universe = function() {
return instance;
}
}
缺点:prototype只能使用第一个实例定义之前的
3. 调整后
function Universe() {
var instance;
Universe = function() {
return instance;
}
Universe.prototype = this;
Universe.constructor = Universe;
instance = new Universe();
instance.start_time = 0;
instance.bang = "big";
return instance;
}
4. 使用闭包调整
var Universe;
(function () {
var instance;
Universe = function() {
if(instance) {
return instance;
}
instance = this;
this.start_time = 0;
this.bang = "big";
}
}());