0
点赞
收藏
分享

微信扫一扫

js实现单例模式

新鲜小饼干 2022-09-02 阅读 197


容易被忽略的地方,是类的原型。所以在构造函数里,需要小心


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');



举报

相关推荐

0 条评论