闭包实现单例模式

内容非原创,内容为《JavaScript模式》第七章设计模式中单例模式的内容,根据书的内容和自己的理解进行了更清晰(?)的阐述

单例模式的思想在于保证一个特定类有且仅有一个实例

JavaScript中可以通过闭包实现单个实例

function Universe() {
    //缓存实例
    var _this = this;
    //正常进行
    this.start_time = 0;
    this.bang = 'big';
    //重写构造函数
    Universe = function () {
        return _this;
    };
}

const uni1 = new Universe();
const uni2 = new Universe();
console.log(uni1 === uni2); //true
复制代码

但是这样会丢失所有在初始定义和重定义时刻之间添加到它里面的属性

function Universe() {
    //缓存实例
    var _this = this;
    //正常进行
    this.start_time = 0;
    this.bang = 'big';
    //重写构造函数
    Universe = function () {
        return _this;
    };
}

Universe.prototype.nothing = true;

const uni1 = new Universe();

Universe.prototype.everything = true;

const uni2 = new Universe();

console.log(uni1.nothing);      //true
console.log(uni2.nothing);      //true
console.log(uni1.everything);   //undefined
console.log(uni2.everything);   //undefined
console.log(uni1.constructor === Universe); //false
复制代码

咦。为什么会发生这样的情况呢。

我们来看看

当如果只是普通的构造函数的时候

这就是

function Universe() {
    //正常进行
    this.start_time = 0;
    this.bang = 'big';
}
Universe.prototype.nothing = true;
Universe.prototype.everything = true;
const uni1 = new Universe();
const uni2 = new Universe();
复制代码

其实例和原型之间的关系

但是构造函数进行了重写之后

function Universe() {
    //缓存实例
    var _this = this;
    //正常进行
    this.start_time = 0;
    this.bang = 'big';
    //重写构造函数
    Universe = function () {
        return _this;
    };
}

Universe.prototype.nothing = true;
const uni1 = new Universe();
Universe.prototype.everything = true;
const uni2 = new Universe();
复制代码

没执行实例化Universe时是这样的

执行完实例化之后

因为uni1是实例化Universe(未重写前的)的实例,所以它的prototype指向了原来的构造函数的原型,在重写之后,Universe指向了新的构造函数,而不是原来的构造函数,而拥有了新的原型,而此时再添加属性只会添加到新的构造函数的原型上,这就能解释为什么之前的uni1.everything输出的undefined。

所以要在第一次实例化的时候还得把此时的constructor和prototype进行修改

function Universe() {
    //缓存实例
    var _this;

    //重写构造函数
    Universe = function () {
        return _this;
    };
    //保留原型属性
    Universe.prototype = this;
    
    //实例
    _this = new Universe();
    _this.constructor = Universe;

    //正常进行
    this.start_time = 0;
    this.bang = 'big';
    
    return _this;
}

Universe.prototype.nothing = true;

const uni1 = new Universe();

Universe.prototype.everything = true;


console.log(uni1.nothing);      //true
console.log(uni1.everything);   //true
console.log(uni1.constructor === Universe); //true
复制代码

咦,好像有点乱,来我们慢慢看

实例化的时候执行到line10的时候,此时修改了当前原型

然后让_this实例化新的Universe对象,此时

这时再重置构造函数指针( _this.constructor = Universe ),此时

此时保留的就是旧构造函数的原型,和新的构造函数(旧的构造函数和新的构造函数的原型就可以去掉了...)

所以此时在向原型添加属性

这样就完成了用闭包实现单例模式~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值