如何防止构造函数在javascript中生成单例实例?

时间:2017-11-11 07:42:02

标签: javascript

如何防止构造函数在javascript中生成单例实例

var Singleton = (function () {
var instance;

function createInstance() {
    var object = new Object("I am the instance");
    return object;
}

return {
    getInstance: function () {
        if (!instance) {
            instance = createInstance();
        }
        return instance;
    }
};
})();

function run() {

   var instance1 = Singleton.getInstance();
   var instance2 = Singleton.getInstance();

   alert("Same instance? " + (instance1 === instance2));  
}

0 个答案:

没有答案