闭包实现单例模式

1,420 阅读2分钟

内容非原创,内容为《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 ),此时

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

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

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