您的位置:首页 > Web前端 > JavaScript

js实现单例模式

2016-06-19 16:24 351 查看
容易被忽略的地方,是类的原型。所以在构造函数里,需要小心

function Universe()
{
// the cached instance
var instance;
// rewrite the constructor
Universe = function Universe() {
return instance;
};

// carry over the prototype properties
Universe.prototype = this;
// the instance
instance = new Universe();
// reset the constructor pointer
instance.constructor = Universe;
// all the functionality
instance.start_time = 0;
instance.bang = "Big";
return instance;

};

var uni = new Universe();
var uni2 = new Universe();

if (uni == uni2)
{
console.log('same');
uni.bang = 'hay';
console.log(uni2.bang);
}
else
console.log('diff');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: