当我们需要利用 js 创建一个类的唯一对象时,应该如何实现呢?
这时单例模式的价值就体现出来了,在学习单例模式之间 先看看这个代码
function Cat () {
}
Cat.prototype.run = function () {
console.log('run run');
}
var cat = new Cat();
cat.run();
运行结果当然是:
run run
那运行这个代码呢?
function Cat () {
return this;
}
Cat.prototype.run = function () {
console.log('run run');
}
var cat = new Cat();
cat.run();
结果也是:
run run
你会发现 Cat 函数内不管是否含有
return this; 用 new关键字生成的 cat 都能调用 run方法。
也就是说这个函数内部默认是有 return this; 这个代码的 ,在 函数外部 this赋值给 cat ,这时cai就可以调用 run 方法了。
明白这一点实现单例模式就变得简单了,只要我们在生成对象时 返回的都是同一个 this 就可以实现单例
首先想到的是利用全局变量保存这个this 像这样
function Cat () {
if(typeof single_instance == 'undefined'){
single_instance = this;
}
return single_instance;
}
Cat.prototype.run = function () {
console.log('run run');
}
var cat1 = new Cat();
var cat2 = new Cat();
console.log(cat1 === cat2);
打印结果是: true
这时我们就实现了单例模式
但是这里存在一个问题,利用全局变量保存this, 它就可能被覆盖掉,也有覆盖掉别的对象的可能。
那就不能用全局变量保存this,我们可以将这个this利用构造本身属性进行保存
这是实现代码
function Cat () {
if( !Cat.single_instance ){
Cat.single_instance = this;
}
return Cat.single_instance;
}
Cat.prototype.run = function () {
console.log('run run');
}
var cat1 = new Cat();
var cat2 = new Cat();
console.log(cat1 === cat2);
利用这种方法实现单例模式 Cat的属性是公开的 也存在被修改的风险
只是比利用全局变量哪种方法好点
实现单利模式 推荐最后一种方法