SOURCE

class Single{
    constructor(name) {
        this.name = this;
        this.instance = null;
    }
    static getInstance(name) {
        if(!this.instance) {
            this.instance = new Single(name)
        }
        return this.instance
    }
}

let a = Single.getInstance()
let b = Single.getInstance()
console.log(a === b)

// es5
var Singleton1 = function(name) {
    this.name = name;
    this.instance = null;
}
Singleton1.getInstance = function(name) {
    if(!this.instance) {
        this.instance = new Singleton1(name);
    }
    return this.instance;
}
var c = Singleton1.getInstance('sven1');
var d = Singleton1.getInstance('sven2');
// 指向的是唯一实例化的对象
console.log(a === b);

// 闭包实现
var Single2 = (function() {
    var instance = null;
    function Single(name) {
        this.name = name;
    }
    return function(name){
        if (!instance) {
            instance = new Single(name);
        }
        return instance;
    };
})();
var oA = new Single2('hi');
var oB = new Single2('hello');
console.log(oA === oB);
console 命令行工具 X clear

                    
>
console